在Spring4之后要使用注解开发,必须保证aop包导入了
在使用注解需要导入context约束,增加注解的支持。
<?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>
1.bean
//等价于 <bean id="user" class="com.my.pojo.User"/>
@Component
public class User {
public String name="aaa";
}
2.属性如何注入
也可在set方法上注入。
@Component
public class User {
@Value("aaa")
public String name;
}
3.衍生的注解
@Conponent有几个衍生注解,我们在web开发中 ,会按照mvc三层框架分层!
#pojo 【@Conponent】
#dao 【@Repository】
#service 【@Service】
#controller 【@Controller】
它们四个是等价的,都会被装配到Spring中。
4.自动装配
5.作用域
@Component
@Scope("singleton")
public class User {
@Value("aaa")
public String name;
}
6.小结
xml与注解:
xml更加万能,适用于任何场合,维护简单方便
注解:不是自己类使用不了,维护复杂
xml用来管理bean;
注解只负责完成属性的注入。
我们在使用过程中,只需要注意一个问题:开启注解支持和指定扫描包。