使用注解开发
- 在Spring4之后,要使用注解开发,必须要保证aop的包导入
org.springframework:spring-aop:5.2.0.RELEASE
- 使用注解需要导入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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--开启注解支持-->
<context:annotation-config/>
</beans>
1.bean
2.属性如何注入
//等价于<bean id="name" class="com.faq.pojo.User"/>
//@Component组件,放在类上,说明这个类被Spring管理了,就是bean
@Component
public class User {
//等价于<property name="name" value="kuangshen"/>
//也可以注入在setName方法上
@Value("kunagshen")
public String name;
// public String name="狂神";
}
3.衍生的注解
@component有几个衍生注解,我们在web开发中,会按照mvc三层架构分层!
- dao【@Repository】
- service【@Service】
- controller【@Controller】
这四个注解功能都是一样的,都是代表将某个类注册到Spring中,装配Bean
4.自动装配置
- @Autowired:自动装配通过类型、名字。如果@Autowired不能唯一自动装配上属性,则需要通过@Qualifier(value=“xxx”)去配置@Autowired的使用,指定一个唯一的bean对象注入
- 定义了Autowired的required属性为false,说明这个对象可以为null,否则不允许为空
@Autowired(required = false) - @Resource:自动装配通过名字、类型。
5.作用域
@Scope("singleton")
public class User {}
6.小结
xml与注解:
- xml更加万能,适用于任何场所!维护简单方便
- 注解不是自己类使用不了维护相对复杂
xml和注解的最佳实践:
- xml用来管理bean;
- 注解只负责完成属性的注入
- 在使用过程中需要注意一个问题:要让注解生效,,需要开启注解的支持
<!--指定要扫描的包,这个包下的注解就会生效-->
<context:component-scan base-package="com.faq"/>
<!--开启注解支持-->
<context:annotation-config/>