spring注解
1.XML配置
<context:annotationconfig/>
@Autowired
注解可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。
当不能确定 Spring 容器中一定拥有某个类的 Bean 时,可以在需要自动注入该类 Bean 的地方可以使用 @Autowired(required = false)
,这等于告诉 Spring:在找不到匹配 Bean 时也不报错。
使用@Qualifier注释指定注入Bean的名称.@Qualifier
只能和 @Autowired
结合使用,是对 @Autowired
有益的补充。
Spring 不但支持自己定义的 @Autowired
的注释,还支持几个由 JSR-250 规范定义的注释,它们分别是 @Resource
、@PostConstruct
以及 @PreDestroy
。
@Resource
的作用相当于 @Autowired
,只不过 @Autowired
按 byType 自动注入,面@Resource
默认按 byName 自动注入罢了。@Resource
有两个属性是比较重要的,分别是 name 和 type,Spring 将@Resource
注释的 name 属性解析为 Bean 的名字,而 type 属性则解析为 Bean 的类型。所以如果使用 name 属性,则使用 byName 的自动注入策略,而使用 type 属性时则使用 byType 自动注入策略。如果既不指定 name 也不指定 type 属性,这时将通过反射机制使用 byName 自动注入策略。
Resource 注释类位于 Spring 发布包的 lib/j2ee/common-annotations.jar 类包中
2.注解配置
需要在spring的xml中通过以下方式配置要扫描的类包:
-------
<?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.baobaotao"/> </beans>
-------
添加类过滤:
-------
<context:component-scan base-package="com.test"> <context:include-filter type="regex" expression="com.test.service..*"/> <context:exclude-filter type="aspectj" expression="com.test.util..*"/> </context:component-scan>
------
使用@Repository
、@Service
和@Controller
分别对持久层、业务层和控制层进行注释。使用@Component
对其他类进行注释。
对需要注入的属性上添加@Autowired.
@Component
有一个可选的入参,用于指定 Bean 的名称,默认情况下,Bean都是singleton的,所以需要注入Bean的地方仅通过 byType 策略就可以自动注入了,所以指定Bean的名称并不常用。
如果需要使用其它作用范围的 Bean,可以通过@Scope
注释来达到目标:
----
package com.springtest;
import org.springframework.context.annotation.Scope;
…
@Scope("prototype")
@Component("person")
public class Person {
…
}
----