基于注解的IOC
Spirng中ioc的常用注解
基于注解的IOC需要重新配置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">
<!-- base-package:告知spring在创建容器时要扫描的包-->
<context:component-scan base-package="service.impl"></context:component-scan>
</beans>
用于创建对象的
- @Component
作用:把当前类对象存入spring容器中
属性:value(用于指定bean的id,默认值为类名且首字母小写) - @Controller
同上,一般用于表现层 - @Service
同上,一般用于业务层 - @Repository
同上,一般用于持久层
用于注入数据的
使用注解注入数据,set方法就不是必须的了
以下三个注解都只能注入其他bean类型的数据,而基本类型和String类型无法使用下面的注解实现。同时,集合类型的注入只能通过xml来实现。
-
@Autowired
作用:自动按照类型注入。
只要容器中有唯一的一个bean对象类型和要注入的变量类型匹配,就可以注入成功,如果没有则报错,如果不唯一会匹配变量名和bean的id,有匹配成功的注入,没有则报错。(好好理解)。
出现位置:可以是变量上,也可以是方法上。 -
@Qualifier
作用:再按照类中注入的基础上再按照名称注入,在给类成员注入时不能单独使用(要和Autowired一起使用),但是再给方法参数注入时可以。
属性:value(用于指定注入bean的id) -
@Resource
作用:直接按照bean的id注入,可以单独使用
属性:name(用于指定bean的id) -
@Value
作用:用于注入基本类型和String类型的数据
属性:value(用来指定属性的值,可以使用spring的el表达式 “${}” )
用于改变作用范围的
- @Scope
作用:用于指定bean的作用范围
属性:value(指定范围的取值:singleton/prototype,默认是单例)
和声明周期相关的
和在bean标签中使用init-method和destroy-method的作用一样,初始化方法和销毁方法。
- @PreDestroy
作用:用于指定销毁方法 - @PostConstruct
作用:用于指定初始化方法
IOC的案例
完全xml
结构
代码:
基于xml案例,github
半xml半注解
完全注解
- @Configuration
表名当前类是一个配置类
当配置类作为AnnotationConfigApplicationContext的参数时,该注解可以不写 - @ComponentScan
用于指定spring创建容器时需要扫描的包
属性:value[]、basePackages[](这两个用谁都行) - @ComponentScans
用于指定多个包,里面是@ComponentScan数组 - @Bean
用于把当前方法的返回值当做bean对象,存入spring的ioc容器中
属性:name(用于指定bean的id,默认是方法名称) - @Import
用于导入其他配置类,导入的是子配置类
属性:value[] (其他配置类) - @PropertySource
用于指定properties的位置
属性:value(指定文件的名称和路径,关键字:classpath,表示文件在类路径下)
在使用注解配置方法时,如果方法有参数,spring框架会去容器中查找有没有可用的bean对象。查找的方式和Autowired注解的作用一样。
/**
* 该类是一个配置类,和bean.xml作用相同
*/
@Configuration
@ComponentScan("com.wxy")
//classpath表示在类路径下
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.uname}")
private String username;
@Value("${jdbc.pwd}")
private String pwd;
/**
* 用于返回一个QueryRunner对象
* @param dataSource
* @return
*/
@Bean(name = "runner")
@Scope("prototype")
public QueryRunner createQueryRunner(DataSource dataSource){
return new QueryRunner(dataSource);
}
/**
* 创建数据源对象
* @return
*/
@Bean(name = "dataSource")
public DataSource createDataSource(){
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
try {
comboPooledDataSource.setDriverClass(driver);
comboPooledDataSource.setJdbcUrl(url);
comboPooledDataSource.setUser(username);
comboPooledDataSource.setPassword(pwd);
} catch (Exception e){
throw new RuntimeException("创建连接池失败");
}
return comboPooledDataSource;
}
}
测试:
@Test
public void testfindAll() {
//获取容器
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
IAccountService as = ac.getBean("accountService",IAccountService.class);
List<Account> accountList = as.findAllAccount();
for(Account account : accountList){
System.out.println(account);
}
}
Spring整合Junit
为了能在单元测试时使用ioc容器,需要spring整合junit.
- 导入spring整合junit的jar(坐标)
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.3.RELEASE</version>
<scope>test</scope>
</dependency>
-
使用Junit提供的一个注解把原有的main方法替换了,替换成spring提供的
@Runwith -
告知spring的运行器,是基于xml还是注解,同时说明位置
@ContextConfiguration
属性:localtions(指定xml文件的位置,加上classpath关键字,表示在类路径下);class(指定注解类所在位置)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {
//--------测试方法
}
- 测试
注意:当我们使用spring 5.x版本时,要求junit的jar必须是4.12及以上。