在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:component-scan base-package="com.sunfl.pojo"/> <context:annotation-config/></beans>
- bean
属性如何注入
//等价于 <bean id="user" class="com.sunfl.pojo.User"/>@Componentpublic class User { public String name; //相当于<property name="name" value="向日葵"> @Value("向日葵") public void setName(String name) { this.name = name; }}
衍生的注解
@Component有几个衍生注解,咱们在web开发中,会依照mvc三层架构分层- dao 【@Repository】
- service 【@Service】
- controller 【@Controller】
这四个注解性能都是一样的,都是代表将某个类注册到Spring容器中,拆卸Bean
主动装配置
- @Autowired:主动拆卸通过类型、名字
- @Nullable:字段标记了这个注解,阐明这个字段能够为null
- @Resource:主动拆卸通过类型、名字
作用域
@Component@Scope("prototype")public class User {}
小结
xml与注解比照:- xml更加万能,实用于任何场合!保护简略不便
- 注解 不是本人类应用不了,保护绝对简单
最佳实际:
- xml用来治理bean
- 注解只负责实现属性的注入