Spring(11)-使用注解开发
使用注解开发
依然使用xml配置文件来管理
spring4之后,要使用注解开发,必须保证aop的包导入了
使用注解开发,要导入context约束,提供注解的支持
1 |
|
-
bean
1
2
3
4
5
6:
//组件,在创建的类前面加上这个注解,说明这个类已经被spring管理了,相当于:
//<bean id="person" class="com.ajream.pojo.Person">
//没有参数时,只能以getBean("类名的小写字母") 来获取bean
//有参数时,可以用getBean("xxx") 来获取beanPerson类:
1
2
3
4
5
6
7
8
9package com.ajream.pojo;
import org.springframework.stereotype.Component;
//没有参数时,只能以getBean("person") 来获取bean
public class Person {
public String name = "张三";
} -
属性注入
1
2:
//相当于<property name="name" value="李四" />1
2
3
4
5
6
7
public class Person {
//注入属性值
public String name;
}也可以在setter方法前使用:
1
2
3
4
5
6
7
8
9
public class Person {
public String name;
public void setName(String name) {
this.name = name;
}
} -
衍生注解
@Component有几个衍生注解,在web中一般按照mvc三层架构划分:
- dao层:@Repository
- service层:@Service
- Controller层:@Controller
这4个注解功能一样的
-
作用域scope
单例
1
2
3
4
5
6
7
8
9
10
public class Person {
public String name;
public void setName(String name) {
this.name = name;
}
}原型
1
-
小结:
xml与注解
-
xml:万能
-
注解:不是自己的类用不了,维护相对复杂
xml与注解最佳实践:
-
xml用来管理bean
-
注解只负责属性注入
-
注意:要让注解生效,必须开启注解的支持
1
2<context:annotation-config/>
<context:component-scan base-package="com.ajream.pojo"/>
-
使用Java的方式配置spring
在此前一直都使用beans.xml配置文件来配置spring如属性注入,现在可以不使用xml了,将spring配置全权交由Java来配置
用MyConfig类来代替beans.xml:
1 | package com.ajream.config; |
Person类:
1 | package com.ajream.pojo; |
MyTest类
这里不使用xml配置文件了,使用Java配置类 MyConfig
1 | import com.ajream.config.MyConfig; |
由于MyConfig类也是配置类,所以它具有beans.xml的功能,比如:
评论