Spring中bean注入相关注解
Spring中bean注入相关注解
组件注解分类
spring中除了提供 @Component 注释外,还定义了几个拥有特殊语义的注释,它们分别是:@Repository、@Service,@Resource 和 @Controller。
这几个注释是等效的,都是将被标记的类注册为bean,只不过在名字上区别这些类的用途
@Service用于标注业务层组件
@Controller用于标注控制层组件(如struts中的action)
@Repository用于标注数据访问组件,即DAO组件
@Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。
比如
@Service
public class VentorServiceImpl implements iVentorService {}
@Repository
public class VentorDaoImpl implements iVentorDao {}
注解生效
在一个稍大的项目中,如果组件采用xml的bean定义来配置,显然会增加配置文件的体积,查找以及维护起来也不太方便。 因此Spring引入了组件自动扫描机制,他在类路径下寻找标注了上述注解的类,并把这些类纳入spring容器中管理。它的作用和在xml文件中使用bean节点配置组件时一样的。要使用自动扫描机制,我们需要在配置文件中加入以下标签<context:component-scan base-package=”package-name”>
:
<?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-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:component-scan base-package=”com.eric.spring”>
</beans>
component-scan标签默认情况下自动扫描指定路径下的包(含所有子包),将带有@Component、@Repository、@Service、@Controller标签的类自动注册到spring容器。对标记了Spring的@Required、@Autowired注解,和JSR250的 @PostConstruct、@PreDestroy、@Resource注解,和JAX-WS的@WebServiceRef注解,以及 @EJB、JPA的@PersistenceContext、@PersistenceUnit等注解的类进行对应的操作使注解生效(包含了annotation-config标签的作用)。
getBean的默认名称是类名(头字母小写),如果想自定义,可以@Service(“bean-id”)
这样来指定。这种bean默认是“singleton”的,如果想改变,可以使用@Scope(“prototype”)
来改变。
可以使用以下方式指定初始化方法和销毁方法:
@PostConstruct
public void init() {
}
@PreDestroy
public void destory() {
}
装配bean
Spring提供@Autowired注解用来装配bean。该注解可以写在字段上,或写在setter方法上。
bean注入时不要new 这个注入的类,因为spring会自动注入,如果手动再new的话会出现错误。被注入的变量加上@Autowired后不需要getter()和setter()方法,这两个方法Spring也会自动注入。
@Autowired默认按类型装配,默认情况下必须要求依赖对象必须存在,如果要允许null值,可以设置它的required属性为false,@Autowired(required=false)` 。如果我们想使用名称装配可以结合@Qualifier注解进行使用。当接口存在两个实现类的时候也必须使用@Qualifier指定注入哪个实现类。
@Component("chinese")
public class Chinese
@Autowired
@Qualifier("chinese")
private Man man;
@Resource 是JDK1.6支持的注解,默认按照名称进行装配,名称可以通过name属性进行指定,如果没有指定name属性,当注解写在字段上时,默认取字段名,按照名称查找,如果注解写在setter方法上默认取属性名进行装配。当找不到与名称匹配的bean时才按照类型进行装配。但是需要注意的是,如果name属性一旦指定,就只会按照名称进行装配。该注解在Spring应用中实际上也是Spring提供的注解处理器处理的。
参考
- 点赞
- 收藏
- 关注作者
评论(0)