日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

使用注解配置spring如@Compnent、@Service、@Consroller、@scope和@value的使用

發(fā)布時間:2024/8/23 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 使用注解配置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>

在類中使用注解完成配置

  • 將對象注冊到容器
  • @Component("user")@Service("user") // service層@Controller("user") // web層他們?nèi)齻€只是名字不同都實現(xiàn)了把user添加到組件中,區(qū)別只是通過名稱可以知道該邏輯是在哪一個層次中

    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)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。