Spring-使用注解开发
sjyvv 2020-01-07 12:20:40
spring
在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="ann"/>
</beans>
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# bean
@Component
//相当于 <bean id="user" class="ann.User"/>
@Component
public class User {
private String name = "haha";
public void setName(String name) {
this.name = name;
}
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 属性如何注入
@Value
@Component
public class User {
//相当于 <property name="name" value="haha"/>
@Value("hah")
private String name;
// @Value("aa") //也可以在这里注解
public void setName(String name) {
this.name = name;
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# 衍生的注解
@Component有几个衍生注解,在web开发中,一般按照MVC三层架构分层
- dao【@Repository】
- service【@Service】
- controller【@Controller】
这四个注解功能都是一样的,都是代表将某个类注册到Spring中,装配Bean
# 自动装配
- @Autowired
- @Nullable
- @Resource
# 作用域
@Scope
@Component @Scope("singleton") //或者prototype public class User { @Value("hah1") private String name; public void setName(String name) { this.name = name; } }
1
2
3
4
5
6
7
8
9
10# 小结
xml与注解:
- xml更加万能,适用于任何场合,维护更加方便
- 注解不是自己的类使用不了,维护相对复杂
xml与注解的最佳实践:
- xml用来管理bean
- 注解只负责完成属性的注入
- 我们在使用的过程中,只需要注意一个问题:必须让注解生效,就需要开启注解的支持