使用注解进行Bean的配置管理
首先导入jar包和原来jar 没有区别
1、 Bean的注解配置及自动扫描
Spring2.5引入,通过@Component 定义框架中Bean
例:@Component("helloService") 等价于 <beanid="helloService" class="cn.itcast.beans.HelloService"/>
public class HelloService {
publicvoid sayHello() {
System.out.println("hellospring annotation....");
}
}
配置applicationContext.xml 对Bean所在package 进行自动扫描(引用context名称空间)
<beansxmlns="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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config />
<context:component-scan base-package ="cn.itcast.beans"></context:component-scan>
</beans>
Spring2.5 同时提供了 @Component注解等效三个衍生注解
用于web三层开发,便于维护,这三个注解是为了让标注类本身的用途清晰,Spring在后续版本会对其增强
@Repository:用于对DAO实现类进行标注
@Service:用于对Service实现类进行标注
@Controller:用于对Controller实现类进行标注、
2、 Bean属性注入
通过@Value注解为属性注入基本类型的值
@Value("传智播客")
//等价于 <property name="company" value="传智播客" />
publicvoid setCompany(String company) {
this.company= company;
}
对于复杂数据类型,也可以同通过@Value注入
@Value("#{userDAO}")
publicvoid setUserDAO(UserDAO userDAO) {
this.userDAO= userDAO;
}
在实际开发中,如果一Bean引用很多个其Bean,手动注入很麻烦,这时常用的解决方案是自动装配
自动装配注解
@Autowired注解可以完成自动装配,可以针对成员变量或者setter方法(如果针对成员变量,无需提供setter方法)
*默认按照类型注入无论名称为什么,只要类型一样就可以注入
*通过@Autowired的required属性,设置是否一定要找到匹配的Bean默认值为true,找不到就报错
@Qualifier可以设置自动装配按照名称注入
@Resource完成完成自动装配,功能和@Autowired 注解一样
例如:
@Autowired(required= true)
//默认按照类型注入
@Qualifier("userDAO")
//按照名称注入
privateUserDAO userDAO;
等价于
@Resource(name = "userDAO")
privateUserDAO userDAO;
3、 Bean对象作用域、初始化销毁
使用@PostCustruct实现 init-method 效果
使用@PreDestroy 实现 destroy-method 效果
通过@Scope 配置Bean 是单例还是多例
@Service("productService")
@Scope("prototype")//多例
publicclass ProductService {
}
4、 Spring3.0提供新注解
spring3.0 引入 javaconfig 思想,使用一个Java类作为 Spring的配置文件
@Configuration指定POJO类为Spring提供Bean定义信息
@Bean提供一个Bean定义信息
以一个 Java类作为配置文件,通过@Bean 生成某个方法就是一个Bean 工厂方法
例:@Configuration//该类是一个配置类
publicclass BeanConfig {
@Bean(name= "employee")
//相当于实例工厂方法,对employee这个bean 进行初始化
publicEmployee createEmployee() {
Employeeemployee = new Employee();
employee.setCompany("传智");
employee.setName("小王");
returnemployee;
}
}
获取
AnnotationConfigApplicationContextannotationConfigApplicationContext = newAnnotationConfigApplicationContext();
//加载配置Bean
annotationConfigApplicationContext.register(BeanConfig.class);
annotationConfigApplicationContext.refresh();
5、关于xml配置文件和注解的混用
<context:annotation-config/>意思为支持 @Resource、@ PostConstruct、@ PreDestroy、@Autowired
6、三种配置方式使用场景
1、 xml配置
2、 spring2.5 注解配置
3、 spring3.0 注解配置
*如果需要为第三方类(存在jar包中,已经编写好), 注入一个属性,必须使用xml方式
*对于自己编写的类 ,使用xml和spring2.5注解是等价的
*spring3.0注解主要用于Bean的构造极其复杂,3.0注解实际本质上是一个工厂方法(基本不会用到)