Spring 使用注解开发
1、在Spring4之后,使用注解开发需要导入aop包
2、使用注解开发需要导入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:component-scan base-package="cn.anguoke.pojo"/>
<context:annotation-config/>
</beans>
- bean
/**
* @Component 组件 等价于 <bean id="user" class="cn.anguoke.pojo.User"/>
*/
@Component
public class User {
private String name;
}
- 属性如何注入
/**
* @Value("时光") 等价于 <property name="name" value="时光"/> 可以写在set上
*/
@Value("时光")
private String name;
- 衍生的注解
@Component有许多衍生注解,我们在web开发中,会按照mvc三层架构分层!
1、dao【@Repository】
2、service【@Service】
3、controller【@Controller】
这四个注解功能是一样的,都是代表将某个类注册到Spring中 ,配置Bean
- 自动装配置
- 作用域
@Scope("prototype")
public class User {
}
xml与注解
- xml更加的万能,适用于任何场合!维护方便
- 注解 不是自己的类使用不了,维护相对复杂
xml与注解最佳实践: - xml用来管理bean;
- 注解只负责完成属性的注入;