Spring注解

来源:互联网 发布:淘宝采集软件有什么用 编辑:程序博客网 时间:2024/04/28 06:58

一.装配bean基于注解

1. @Component

@component(代替的是<bean class="..."/>)@component("person")(代替的是<bean id="person" class="..."/>)

2.web开发,提供3个@Component注解衍生注解(功能一样)

@Repository :dao层@Service:service层@Controller:web层

3.依赖注入,给私有字段设置,也可以给setter方法设置

普通值:@Value("")引用值:    方式1:按照【类型】注入        @Autowired    方式2:按照【名称】注入1        @Autowired        @Qualifier("名称")    方式3:按照【名称】注入2        @Resource("名称")

4.生命周期

初始化:@PostConstruct销毁:@PreDestroy

5.作用域

@Scope("prototype") 多例

二.Resource注解(引用)

@Resource    private Student student;一定要启动依赖注入的注解解析器 
   <context:annotation-config></context:annotation-config>

原理:

1.Spriing容器启动的时候会创建在applicationContext.xml中的<bean>对象2.Spring容器解析到context:annotation-config时,会在Spring管理的bean的范围内查找这些类的属性上是否有@Resource注解3.Spring解析@Resource的name属性,    如果为空,拿注解所在的属性的名称与Spring容器中的id去匹配,如果匹配成功则赋值,否则,按照类型去匹配,还没有成功,就报错。    如果不为空,则拿name的属性值跟Spring容器中的id去匹配,不成功则报错

三.扫描注解

@Component("student")public class Student {...}@Component("person")public class Person {    @Resource(name="student")    private Student student;    ...}配置文件中:<context:component-scan base-package="com.spring.scan"></context:component-scan>

原理

1.启动Spring容器,Spring容器解析配置文件2.Spring解析到context:component-scan ,会在指定的base-package包及子包中扫描所有的类,看哪些类上有@Commonent注解3.其实相当于将注解解析成<bean/>
0 0
原创粉丝点击