Spring中常用注解篇
这篇文章用来总结Spring常用注解,spring 2.5 开始的基于注解配置,通过注解的使用减少配置;
创建对象
@Component
- 作用
把资源交给spring进行管理,等同于我们自己的xml文件中配置bean
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="authority.ssm.dao"/>
</bean>
@Controller、@Service、@Repository
- @Controller-用于表现出
- @Service-用于业务层注解
- @Repository用于持久层
如果注解中有且只有一个属性value要赋值时,value在赋值时可以不写
@Repository("userDao")
注入数据
相当于:
<property name="" ref="">
<property name="" value="">
@Autowired
自动按照类型注入,当使用注解注入属性时, set 方法可以省略;
当有多个类型匹配时,使用要注入的对象变量名称作为 bean 的 id
@Qualifier
- 作用
在自动按照类型注入的基础之上,再按照 Bean 的 id 注入。它在给字段注入时不能独立使用,必须和@Autowired 一起使用;
给方法参数注入时,可以独立使用
- 属性value:指定bean的id
@Resource
- 作用
直接按照Bean的id注入
- 属性name:指定bean的id
@Value
- 作用
注入基本数据类型和String类型数据
- 属性value:用于指定值
改变作用范围
通过value属性,指定bean的作用范围(指定bean的作用域)
取值:
singleton
prototype
request
session
globalsession