基于上一讲XML配置改造使用注解:
bean.xml里面的内容:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="com.hr"></context:component-scan> <!-- 配置QueryRunner--> <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype"> <!-- 注入数据源--> <constructor-arg name="ds" ref="dataSource"></constructor-arg> </bean> <!-- 配置数据源--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/eesy"></property> <property name="user" value="root"></property> <property name="password" value="123456"></property> </bean> </beans>改造1: 项目代码: https://github.com/2402zmybie/spring02_account_ioc_anno 至此,改造完毕, 下一讲, 直接去掉配置文件bean.xml. 纯注解实现配置类, 笔记:
/** * 该类是一个配置类, 它的作用和bean.xml是一样的 * Configuration: 指定当前类是一个配置类 * ComponentScan: * 作用:用于通过注解指定spring在创造容器时要扫描的包 * 属性: * value:它和basePackages的作用是一样的,都是用于指定创建容器时要扫描的包 * <context:component-scan base-package="com.hr"></context:component-scan> * Bean: * 作用: 用于把当前方法的返回值作为bean对象存入spring的ioc容器中 * 属性: * name: 用于指定bean的id, 当不写时, 默认值是当前方法的名称 * 细节: * 当我们使用注解配置方式时,如果方法有参数,spring框架会去容器中查找有没有可用的bean对象,查找的方式和Autowired注解的作用一样 * Import: * 作用: 用于导入其他的配置类 * 属性: * vaule:用于指定其他配置类的字节码, 使用Import的注解之后, 有Import注解的类就是父配置类,而导入的都是子配置类 * PropertySource: * 作用: 用于properties文件的位置 * 属性: * value: 指定文件的名称和路径 * 关键字: classpath: 表示类路径下 */ @Configuration @ComponentScan(value = {"com.hr"}) @Import({JdbcConfig.class}) @PropertySource("classpath:jdbcConfig.properties") public class SpringConfiguration { }项目地址: https://github.com/2402zmybie/spring02_account_annoioc_withoutxml