基于注解的IOC配置
创建对象
作用与xml配置文件中的<bean>
标签实现的功能是一样的
@Component
:- 作用: 用于把当前类对象存入Spring容器中
- 属性:
value
: 用于指定bean的id
,默认值为当前类名(首字母改为小写)
以下三种作用和属性和@Component
是一样的,是Spring框架提供的明确三层使用的注解。
@Controller
: 一般用在表现层@Service
: 一般用在业务层@Repository
: 一般用在持久层
当三层都不属于的对象可以选择使用@Component
注入数据
作用与在xml配置文件中<bean>
标签里写一个<property>
是一样的
@Autowired
- 作用:
- 按照类型注入,只要容器中有唯一的一个bean对象类型和注入的变量类型匹配,就能成功注入
- 如果IOC容器中没有任何bean的类型和要注入对象的类型匹配,则报错
- 如果IOC容器中有多个bean的类型和要注入对象匹配时:
- 被注入的对象和其中一个bean的名称相同时,可以将名字相同的注入
- 被注入的对象和所有的bean的名称不同时,会因为不知道选择哪个而报错
- 出现位置: 可以是变量上,也可以是方法上
- 细节: 使用注解注入,set方法不是必须的
@Qualifier
- 作用: 在按照类中注入的基础之上再按照名称注入,它在给成员变量注入时不能单独使用(要和
@AutoWired
注解一起使用),但是在给方法参数注入时可以 - 属性:
value
: 用于指定注入bean的id
给方法使用的例子
当有多个数据源可以使用时,你可以用@Qualifier
注解添加你想要的那个,此时@Qualifier
可以单独使用1
2
3
4
5@Bean("runner")
@Scope("prototype")
public QueryRunner createQueryRunner(@Qualifier("dataSource1") ComboPooledDataSource dataSource) {
return new QueryRunner(dataSource);
}
@Resource
- 作用: 直接按照bean的id注入,可以独立使用
- 属性:
name
: 用于指定bean的id
以上三种注入方式都只能注入其他bean类型的数据,不能注入String和基本类型,其中集合类型的注入只能通过xml配置的方式实现
@Value
- 作用: 用于注入基本类型和String类型的数据
- 属性:
value
: 用于指定数据的值,它可以使用Spring中SpringEL表达式
作用范围
作用与在<bean>
标签中使用scope
属性实现的功能是一样的
@Scope
- 作用:用于指定bean的作用范围
- 属性:
value
: 指定作用范围的取值- 常用取值:
singleton
(默认): 单例prototype
: 多例
- 常用取值:
生命周期(了解)
作用与<bean>
标签中使用init-method
和destroy-method
的作用是一样的
@PostConstruct
- 作用: 用于指定初始化方法
@PreDestroy
- 作用: 用于指定销毁方法
实现注解IOC配置需要的操作
告知Spring在创建容器时需要扫描的包,配置所需的标签不是在beans的约束中,而是一个叫context名称空间和约束中
为bean.xml添加约束(在Spring官方文档中搜索xmlns:context)
1
2
3
4
5
6
7
8
9
10
11
12<?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:annotation-config/>
</beans>加入
<context:component-scan base-package="com.xushui"></context:component-scan>
语句,来对指定目录的包进行扫描
引入注入数据
1 | @Component("accountService") |
直接在测试类中调用方法,会有java.lang.NullPointerException
(空指针异常),所以我们还需要注入数据
Spring新注解
@Configuration
- 作用: 指定当前类为配置类
- 细节: 当配置类作为
AnnotationConfigApplicationContext
方法的参数时,可以不写
@ComponentScan
- 作用: 用于通过注解指定Spring在创建容器时要扫描的包
- 属性:
value
: 他和basePackages的作用是一样的,等同于在xml里配置了<context:component-scan base-package="com.xushui"></context:component-scan>
@Bean
- 作用: 用于把当前方法的返回值作为bean对象存入到Spring的IOC容器中
- 属性:
name
: 用于指定bean的id,默认值是当前方法的名称
- 细节: 当我们使用注解配置方法时,如果方法有参数,Spring框架会去容器中查找有没有可用的bean对象
- 查找的方式和Autowired注解的作用是一样的
其他注解
@Import
- 作用: 用于导入其他的配置类
- 属性:
value
: 用于指定其他配置类的字节码- 有Import注解的配置类就为主配置类,而导入的都是子配置类
@PropertySource
- 作用: 用于指定
properties
文件的位置 - 属性:
value
: 指定文件的名称和路径- 关键字:
classpath
,表示类路径下
- 关键字:
小案例
xml案例
bean.xml1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="accountService" class="com.xushui.service.Impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"></property>
</bean>
<bean id="accountDao" class="com.xushui.dao.Impl.AccountDaoImpl">
<property name="runner" ref="queryRunner"></property>
</bean>
<bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
<constructor-arg name="ds" ref="dateSource"></constructor-arg>
</bean>
<bean id="dateSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring"></property>
<property name="user" value="root"></property>
<property name="password" value="******"></property>
</bean>
</beans>
在bean.xml中配置好后要通过ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
来加载配置文件
注解形式
用了注解后,就不需要set方法,用AutoWired自动配置1
2
3
4
5
6@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {
@Autowired
private QueryRunner runner = null;
...
也可以使用resource注解指定bean对象的id1
2
3
4
5
6@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {
@Resource(name = "runner")
private QueryRunner runner = null;
...
AccountService中也是一样1
2
3
4
5@Service("accountService")
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao = null;
...
最重要的是创建一个配置类1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27/**
* 他是一个配置类,作用和bean.xml一样
* Configuration表示当前类就是配置类
*/
@Configuration
@ComponentScan("com.xushui")
public class SpringConfiguration {
@Bean("runner")
public QueryRunner createQueryRunner(ComboPooledDataSource dataSource) {
return new QueryRunner(dataSource);
}
@Bean("dataSource")
public ComboPooledDataSource createDataSource() {
try {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/spring");
dataSource.setUser("root");
dataSource.setPassword("******");
return dataSource;
} catch (Exception e) {
throw new RuntimeException("数据库连接初始化失败");
}
}
}
当这些都具备了就可以不需要bean.xml了然后通过ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
来加载配置类
小优化
此时当这些都完成了,还有一个要注意的地方是runner此时还是个单例的对象,线程不安全,添加注解@Scope("prototype")
1
2
3
4
5@Bean("runner")
@Scope("prototype")
public QueryRunner createQueryRunner(ComboPooledDataSource dataSource) {
return new QueryRunner(dataSource);
}
可以添加一个jdbc的配置类,用主配置文件加上@Improt
注解的形式导入jdbc的配置类。同时加上@PropertySource
将配置文件加载进来1
2
3
4
5
6
7
8
9
10
11@Import(JdbcConfig.class)
@Configuration
@ComponentScan("com.xushui")
@PropertySource("classpath:jdbc.properties")
public class SpringConfiguration {
@Bean("runner")
@Scope("prototype")
public QueryRunner createQueryRunner(ComboPooledDataSource dataSource) {
return new QueryRunner(dataSource);
}
}
用Spring的el表达式读取配置文件1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28public class JdbcConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean("dataSource")
public ComboPooledDataSource createDataSource() {
try {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
return dataSource;
} catch (Exception e) {
throw new RuntimeException("数据库连接初始化失败");
}
}
}
Spring整合junit的配置
导入Spring整合junit的jar包(坐标)
1
2
3
4
5<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>使用junit提供的一个注解,把原有的main方法替换了,替换成Spring提供的
@Runwith(SpringJunit4ClassRunner.class)
- 告知Spring的运行器,Spring和IOC的创建是基于xml还是注解的,并且说明位置
@ContextConfiguration
- locations: 指定xml文件的位置,加上classpath关键字,表示在类路径下
- classes: 指定注解类所在的位置
在测试类中,就可以通过这几个注解,就可以不用自己导入配置类或配置文件,可以直接使用Spring的IOC容器中的对象1
2
3
4
5
6@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {
@Autowired
private AccountService accountService;
...
需要注意的是Spring5.x版本,只支持4.12版本以上的JUnit