使用注解配置spring如@Compnent、@Service、@Consroller、@scope和@value的使用
生活随笔
收集整理的這篇文章主要介紹了
使用注解配置spring如@Compnent、@Service、@Consroller、@scope和@value的使用
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
步驟
1.導(dǎo)包4+2+spring-aop
如圖:為學(xué)習(xí)到該階段需要用到的包(里面的aop+test是spring和junit整合測試的時候用到的)2.為主配置文件引入新的命名空間(約束)
3.開啟使用注解代理配置文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd "><!-- 指定掃描cn.itcast.bean報下的所有類中的注解.注意:掃描包時.會掃描指定報下的所有子孫包--> <context:component-scan base-package="cn.itcast.bean"></context:component-scan></beans>在類中使用注解完成配置
2.修改對象的作用范圍
@Scope(scopeName="singleton|prototype"3.值類型注入
在聲明是變量前面注入內(nèi)容 @Value("18")private Integer age;通過反射的Field賦值,破壞了封裝性
在聲明set方法前注入內(nèi)容 @Value("瑪莎拉蒂")public void setName(String name) {this.name = name;}
4.引用類型注入
@Autowiredprivate Car car;自動裝配
問題:如果匹配多個類型一致的對象.將無法選擇具體注入哪一個對象.@Qualifier("car2")//使用@Qualifier注解告訴spring容器自動裝配哪個名稱的對象
手動裝配
@Resource(name="car")//手動注入,指定注入哪個名稱的對象5.初始化|銷毀方法
@PostConstruct //在對象被創(chuàng)建后調(diào)用.init-methodpublic void init(){System.out.println("我是初始化方法!");}@PreDestroy //在銷毀之前調(diào)用.destory-methodpublic void destory(){System.out.println("我是銷毀方法!");}總結(jié)
以上是生活随笔為你收集整理的使用注解配置spring如@Compnent、@Service、@Consroller、@scope和@value的使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 爬虫遇到路径转换的解决方案
- 下一篇: Hbase入门篇