美文网首页
Spring 注解解析

Spring 注解解析

作者: 薛云龙 | 来源:发表于2016-03-20 09:46 被阅读181次

@Repository 存储层Bean

首先使用 @Repository 将 DAO 类声明为 Bean
package bookstore.dao;   
@Repository   
public class UserDaoImpl implements UserDao{ …… }   

其次,在xml配置文件中启动Spring的自动扫描功能、
 <beans … > 
……
 <context:component-scan base-package=”bookstore.dao” /> 
……
 </beans> 
效果
如此,我们就不再需要在 XML 中显式使用 <bean/> 进行Bean 的配置。
Spring 在容器初始化时将**自动扫描 base-package 指定的包及其子包下的所有 class文件,所有标注了 @Repository 的类都将被注册为 Spring Bean。

为什么 @Repository 只能标注在 DAO 类上呢?这是因为该注解的作用不只是将类识别为Bean?
同时它还能将所标注的类中抛出的数据访问异常封装为 Spring 的数据访问异常类型。
Spring本身提供了一个丰富的并且是与具体的数据访问技术无关的数据访问异常结构,用于封装不同的持久层框架抛出的异常,使得异常独立于底层的框架。

@Component **
是一个泛化的概念,仅仅表示
一个组件** (Bean) ,可以作用在任何层次
@Service 业务层Bean :
通常作用在业务层,但是目前该功能与 @Component 相同。
@Controller 展示层Bean
通常作用在控制层,但是目前该功能与 @Component 相同。

通过在类上使用 @Repository、@Component、@Service 和 @Constroller 注解,Spring会自动创建相应的 BeanDefinition 对象,并注册到 ApplicationContext 中。
这些类就成了 Spring受管组件。这三个注解除了作用于不同软件层次的类,其使用方式与 @Repository 是完全相同的。

对于包含 name 属性的 @Component、@Repository、 @Service 和@Controller,会把 name 取值作为 Bean 的名字。如果这个注解不包含 name值或是其他被自定义过滤器发现的组件,默认 Bean 名称会是小写开头的非限定类名
**@Autowired **
最后,说说 @Autowired Spring 2.5 引入了 @Autowired 注释,它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。 通过 @Autowired的使用来消除 set ,get方法。

package com.baobaotao;     
public class Boss {     
    // 省略 get/setter     
@Autowired    
private Car car;     

@Autowired    
private Office office;    
  
@Override    
public String toString() {     
    return "car:" + car + "/n" + "office:" + office;     
}     
}     

相关文章

网友评论

      本文标题:Spring 注解解析

      本文链接:https://www.haomeiwen.com/subject/ojahlttx.html