日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

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

發布時間:2024/8/23 43 豆豆
生活随笔 收集整理的這篇文章主要介紹了 使用注解配置spring如@Compnent、@Service、@Consroller、@scope和@value的使用 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

步驟

1.導包4+2+spring-aop

如圖:為學習到該階段需要用到的包(里面的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層他們三個只是名字不同都實現了把user添加到組件中,區別只是通過名稱可以知道該邏輯是在哪一個層次中

    2.修改對象的作用范圍

    @Scope(scopeName="singleton|prototype"

    3.值類型注入

    在聲明是變量前面注入內容 @Value("18")private Integer age;
    通過反射的Field賦值,破壞了封裝性
    在聲明set方法前注入內容 @Value("瑪莎拉蒂")public void setName(String name) {this.name = name;}

    4.引用類型注入

    @Autowiredprivate Car car;

    自動裝配

    問題:如果匹配多個類型一致的對象.將無法選擇具體注入哪一個對象.
    @Qualifier("car2")//使用@Qualifier注解告訴spring容器自動裝配哪個名稱的對象

    手動裝配

    @Resource(name="car")//手動注入,指定注入哪個名稱的對象

    5.初始化|銷毀方法

    @PostConstruct //在對象被創建后調用.init-methodpublic void init(){System.out.println("我是初始化方法!");}@PreDestroy //在銷毀之前調用.destory-methodpublic void destory(){System.out.println("我是銷毀方法!");}

    總結

    以上是生活随笔為你收集整理的使用注解配置spring如@Compnent、@Service、@Consroller、@scope和@value的使用的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。