一,注解开发
前言:在Spring4之后,要使用注解开发,必须保证aop的包导入,(这个包在spring-webmvc里)
使用注解需要导入context约束,增加注解支持
1,bean
2,属性如何注入
//等价于 <bean id="user" class="com.king.pojo.User"/> @Component public class User { //@Value("king") private String name; public String getName() { return name; } @Value("king") public void setName(String name) { this.name = name; } }
3,衍生的注解
@Component有几个衍生注解,在Web开发中,会按照mvc三层架构分层
dao【@Repository】
service 【@Service】
controller【Controller】
功能都是一样的,代表将某个类 注册到Spring中,装配Bean
4,自动装配
@Autowired:放在属性上,自动装配 默认通过类型,后名字
如果Autowired不能唯一自动装配属性,则需同通过@Qualifier(value="xxx")
@Nullable:放在属性上,标记了这个注解,说明这个注解可以为null
@Rescource:放在属性上,自动装配默认通过名字,后类型
5,作用域
@Scope(String name);
6,小结
xml与注解区别:
xml,更加万能,适用于任何场合!维护简单方便
注解,不是自己的类使用不了,维护相对复杂!
最佳实践:
xml用来管理bean
注解只负责完成属性注入(xml注册bean,注解注入属性,目前企业开发常用)
<!--指定要扫描的包,这个包下的注解就会生效--> <context:component-scan base-package="com.king"/> <context:annotation-config/>
二,JavaConfig实现配置
现在完全不需要使用Spring的XML配置了,全权交给Java来做!
JavaConfig是Spring的一个子项目,在Spring4之后,它成为一个核心功能
@Configuration,作用在类上,里面也是被@Component封装的,被Spring容器托管
代表一个配置类,(相当于beans.xml)
@Component,相当于bean
//定义当前类为配置类,相当于applicationContext.xml @Configuration //指定注解生效范围 @ComponentScan("com.king.pojo") //将其它配置类引入 @Import(KingConfig2.class) public class KingConfig { //相当于bean标签 @Bean public User getUser(){ return new User(); } }