spring 注解方式配置Bean

概要:




再classpath中掃描組件

  • 組件掃描(component scanning):Spring可以從classpath下自己主動掃描。偵測和實例化具有特定注解的組件
  • 特定組件包含:
    • @Component:基本注解。標示了一個受Spring管理的組件(能夠混用。spring還無法識別詳細是哪一層)
    • @Respository:建議標識持久層組件(能夠混用。spring還無法識別詳細是哪一層)
    • @Service:建議標識服務層(業務層)組件(能夠混用,spring還無法識別詳細是哪一層)
    • @Controller:建議標識表現層組件(能夠混用,spring還無法識別詳細是哪一層)
  • 對于掃描到的組件,Spring有默認的命名策略:使用非限定類名,第一個字母小寫(UserServiceImpl-》userServiceImpl),也能夠再注解中通過value屬性值標識組件的名稱(通常能夠將UserServiceImpl —》userService,能夠將Impl拿掉,這是一個習慣)

在classpath中掃描組件
  • 當在組件類中使用了特定的注解之后,還須要在Spring的配置文件里聲明<context:component-scan>:
    • base-package屬性指定一個須要掃描的基類包,Spring容器將會掃描整個基類包里及其子包中的全部類
    • 當須要掃描多個包時,能夠使用逗號分隔
    • 假設僅希望掃描特定的類而非基包下的全部類,可使用resource-pattern屬性過濾特定的類。實例:?
    • <context:include-filter>子節點表示要包括的目標類
    • <context:exclude-filter>子節點表示要排除在外的目標類
    • <context:component-scan>下能夠擁有若干個<context:include-filter>和<context:exclude-filter>子節點
    • <context:include-filter>和<context:exclude-filter>子節點支持多種類型的過濾表達式:?

組件裝配
  • <context:component-sacn>元素還會自己主動注冊AutowireAnnotationBeanPostProcessor實例。該實例能夠自己主動裝配具有@Autowired和@Resource、@Inject注解的屬性

使用@Autowired自己主動裝配Bean
  • @Autowired注解自己主動裝配具有兼容類型的單個Bean屬性
    • 能夠放在構造器或普通字段(即使是非public)或一切具有參數的方法都能夠應用@Authwired注解
    • 默認情況下,全部使用@Autowired注解的屬性都須要被設置。當Spring找不到匹配的Bean裝配屬性時,會拋出異常。若某一屬性同意不被設置,能夠設置@Authwired注解的required屬性為false
    • 默認情況下,當IOC容器里存在多個類型兼容的Bean時(@Autowired先是依照類型匹配Bean。假設存在多個類型同樣的Bean,此時IOC容器會去尋找與屬性名同樣名字的Bean),通過類型的自己主動裝配將無法工作,此時能夠在@Qualifier注解里Bean屬性的名稱。Spring同意對方法的方法的輸入參數標注@Qualifier以指定注入Bean的名稱
    • @Authwired注解也能夠應用在數組類型的屬性上。此時Spring將會把全部匹配的Bean進行自己主動裝配
    • @Authwired注解也能夠應用在集合屬性上。此時Spring讀取該集合的類型信息。然后自己主動裝配全部與之兼容的Bean
    • @Authwired注解用在java.util.Map上時,若該Map的鍵值為String,那么Spring將會自己主動裝配與之Map值類型兼容的Bean,此時Bean的名稱作為鍵值

?使用@Resource或@Inject自己主動裝配Bean
  • Spring還支持@Resource和@Inject注解。這兩個注解和@Autowired注解的功能類似
  • @Resource注解要求提供一個Bean名稱的屬性,若該屬性為空,則自己主動採用標注處的變量或方法名作為Bean的名稱
  • @Inject和@Autowired注解一樣也是依照類型匹配注入的Bean,但沒有required屬性
  • 建議使用@Autowired注解


實例代碼具體解釋:
代碼結構

注意:使用注解還須要導入spring-aop-4.0.5.RELEAE.jar這個包


TestObject.java
package com.coslay.beans.annotation;import org.springframework.stereotype.Component;public class TestObject {}


UserController.java
package com.coslay.beans.annotation.controller;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;import com.coslay.beans.annotation.service.UserService;@Controller
public class UserController {@Autowiredprivate UserService userService;public void execute(){System.out.println("UserController execute...");userService.add();}
}



UserService.java
package com.coslay.beans.annotation.service;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;import com.coslay.beans.annotation.reporsitory.UserRepository;@Service
public class UserService {private UserRepository userRepository;//假設有多個類型匹配時。則會去匹配與這個屬性名字同樣的Bean的名字//@Repository("userRepository")//public class UserRepositoryImpl implements UserRepository{//由于名字同樣所以匹配成功//能夠將@Autowired放在字段或者方法上//假設沒有指定名字//另一種方法是使用@Qualifier("userRepositoryImpl")//用來指定哪一個指定名字的Bean//能夠將該標簽放在字段,設置方法或者設置方法的傳入參數前面@Autowired@Qualifier("userRepositoryImpl")public void setUserRepository(UserRepository userRepository){this.userRepository = userRepository;}//	@Autowired
//	public void setUserRepository(@Qualifier("userRepositoryImpl") UserRepository userRepository){
//		this.userRepository = userRepository;
//	}public void add(){System.out.println("UserService add...");userRepository.sava();}
}


UserRepository.java
package com.coslay.beans.annotation.reporsitory;public interface UserRepository {void sava();}



UserRepositoryImpl.java
package com.coslay.beans.annotation.reporsitory;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;import com.coslay.beans.annotation.TestObject;@Repository("userRepository")
public class UserRepositoryImpl implements UserRepository{@Autowired(required=false)private TestObject testObject;@Overridepublic void sava() {System.out.println("UserRepository Save...");System.out.println(testObject);}}


UserJdbcRepository.java
package com.coslay.beans.annotation.reporsitory;import org.springframework.stereotype.Repository;@Repository
public class UserJdbcRepository implements UserRepository {@Overridepublic void sava() {System.out.println("UserJdbcRepository sava...");}}



Main.java
package com.coslay.beans.annotation;import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;import com.coslay.beans.annotation.controller.UserController;
import com.coslay.beans.annotation.reporsitory.UserRepository;
import com.coslay.beans.annotation.service.UserService;public class Main {public static void main(String[] args) {ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-annotation.xml");//		TestObject to = (TestObject) ctx.getBean("testObject");
//		System.out.println(to);
//		UserController userController = (UserController) ctx.getBean("userController");System.out.println(userController);userController.execute();//		
//		UserService userService = (UserService) ctx.getBean("userService");
//		System.out.println(userService);
//		
//		UserRepository userRepository = (UserRepository) ctx.getBean("userRepository");
//		System.out.println(userRepository);}
}


beans-annotation.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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- 指定Spring IOC 容器掃描的包 --> <!-- 能夠通過resource-pattern指定掃描的資源 --> <!-- <context:component-scan base-package="com.coslay.beans.annotation" resource-pattern="reporsitory/*.class"> </context:component-scan> --> <!-- context:exclude-filter 子節點指定排除哪些指定表達式的組件 context:include-filter 子節點指定包括哪些表達式的組件,該子節點須要use-default-filters="false"配合使用(假設use-default-filters="ture"則使用系統默認掃描全部帶有@Component@Controller@Service@Repository的組件) --> <context:component-scan base-package="com.coslay.beans.annotation"> <!-- <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/> --> <!-- <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/> --> <!-- <context:exclude-filter type="assignable" expression="com.coslay.beans.annotation.reporsitory.UserRepository"/> --> <!-- <context:include-filter type="assignable" expression="com.coslay.beans.annotation.reporsitory.UserRepository"/> --> </context:component-scan> </beans>



轉載于:https://www.cnblogs.com/liguangsunls/p/7349604.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/391701.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/391701.shtml
英文地址,請注明出處:http://en.pswp.cn/news/391701.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

主成分分析 獨立成分分析_主成分分析概述

主成分分析 獨立成分分析by Moshe Binieli由Moshe Binieli 主成分分析概述 (An overview of Principal Component Analysis) This article will explain you what Principal Component Analysis (PCA) is, why we need it and how we use it. I will try to make it as simple…

擴展方法略好于幫助方法

如果針對一個類型實例的代碼片段經常被用到&#xff0c;我們可能會想到把之封裝成幫助方法。如下是一段針對DateTime類型實例的一段代碼&#xff1a;class Program{static void Main(string[] args){DateTime d new DateTime(2001,5,18);switch (d.DayOfWeek){case DayOfWeek.…

零元學Expression Blend 4 - Chapter 25 以Text相關功能就能簡單做出具有設計感的登入畫面...

原文:零元學Expression Blend 4 - Chapter 25 以Text相關功能就能簡單做出具有設計感的登入畫面本章將交大家如何運用Blend 4 內的Text相關功能做出有設計感的登入畫面 讓你五分鐘就能快速做出一個登入畫面 ? 本章將教大家如何運用Blend 4 內的Text相關功能做出有設計感的登入…

leetcode 395. 至少有 K 個重復字符的最長子串(滑動窗口)

給你一個字符串 s 和一個整數 k &#xff0c;請你找出 s 中的最長子串&#xff0c; 要求該子串中的每一字符出現次數都不少于 k 。返回這一子串的長度。 示例 1&#xff1a; 輸入&#xff1a;s “aaabb”, k 3 輸出&#xff1a;3 解釋&#xff1a;最長子串為 “aaa” &…

冠狀病毒時代的負責任數據可視化

First, a little bit about me: I’m a data science grad student. I have been writing for Medium for a little while now. I’m a scorpio. I like long walks on beaches. And writing for Medium made me realize the importance of taking personal responsibility ove…

集合_java集合框架

轉載自http://blog.csdn.net/zsw101259/article/details/7570033 Java集合框架圖 簡化圖&#xff1a; Java平臺提供了一個全新的集合框架。“集合框架”主要由一組用來操作對象的接口組成。不同接口描述一組不同數據類型。 1、Java 2集合框架圖 ①集合接口&#xff1a;6個…

顯示隨機鍵盤

顯示隨機鍵盤 1 <!DOCTYPE html>2 <html lang"zh-cn">3 <head>4 <meta charset"utf-8">5 <title>7-77 課堂演示</title>6 <link rel"stylesheet" type"text/css" href"style…

數據特征分析-統計分析

一、統計分析 統計分析是對定量數據進行統計描述&#xff0c;常從集中趨勢和離中趨勢兩個方面分析。 集中趨勢&#xff1a;指一組數據向某一中心靠攏的傾向&#xff0c;核心在于尋找數據的代表值或中心值-統計平均數&#xff08;算數平均數和位置平均數&#xff09; 算術平均數…

心學 禪宗_禪宗宣言,用于有效的代碼審查

心學 禪宗by Jean-Charles Fabre通過讓查爾斯法布爾(Jean-Charles Fabre) 禪宗宣言&#xff0c;用于有效的代碼審查 (A zen manifesto for effective code reviews) When you are coding, interruptions really suck.當您編碼時&#xff0c;中斷確實很糟糕。 You are in the …

leetcode 896. 單調數列

如果數組是單調遞增或單調遞減的&#xff0c;那么它是單調的。 如果對于所有 i < j&#xff0c;A[i] < A[j]&#xff0c;那么數組 A 是單調遞增的。 如果對于所有 i < j&#xff0c;A[i]> A[j]&#xff0c;那么數組 A 是單調遞減的。 當給定的數組 A 是單調數組…

數據eda_銀行數據EDA:逐步

數據edaThis banking data was retrieved from Kaggle and there will be a breakdown on how the dataset will be handled from EDA (Exploratory Data Analysis) to Machine Learning algorithms.該銀行數據是從Kaggle檢索的&#xff0c;將詳細介紹如何將數據集從EDA(探索性…

結構型模式之組合

重新看組合/合成&#xff08;Composite&#xff09;模式&#xff0c;發現它并不像自己想象的那么簡單&#xff0c;單純從整體和部分關系的角度去理解還是不夠的&#xff0c;并且還有一些通俗的模式講解類的書&#xff0c;由于其舉的例子太過“通俗”&#xff0c;以致讓人理解產…

計算機網絡原理筆記-三次握手

三次握手協議指的是在發送數據的準備階段&#xff0c;服務器端和客戶端之間需要進行三次交互&#xff1a; 第一次握手&#xff1a;客戶端發送syn包(synj)到服務器&#xff0c;并進入SYN_SEND狀態&#xff0c;等待服務器確認&#xff1b; 第二次握手&#xff1a;服務器收到syn包…

VB2010 的隱式續行(Implicit Line Continuation)

VB2010 的隱式續行&#xff08;Implicit Line Continuation&#xff09;許多情況下,您可以讓 VB 后一行繼續前一行的語句&#xff0c;而不必使用下劃線&#xff08;_&#xff09;。下面列舉出隱式續行語法的使用情形。1、逗號“&#xff0c;”之后PublicFunctionGetUsername(By…

flutter bloc_如何在Flutter中使用Streams,BLoC和SQLite

flutter blocRecently, I’ve been working with streams and BLoCs in Flutter to retrieve and display data from an SQLite database. Admittedly, it took me a very long time to make sense of them. With that said, I’d like to go over all this in hopes you’ll w…

leetcode 303. 區域和檢索 - 數組不可變

給定一個整數數組 nums&#xff0c;求出數組從索引 i 到 j&#xff08;i ≤ j&#xff09;范圍內元素的總和&#xff0c;包含 i、j 兩點。 實現 NumArray 類&#xff1a; NumArray(int[] nums) 使用數組 nums 初始化對象 int sumRange(int i, int j) 返回數組 nums 從索引 i …

Bigmart數據集銷售預測

Note: This post is heavy on code, but yes well documented.注意&#xff1a;這篇文章講的是代碼&#xff0c;但確實有據可查。 問題描述 (The Problem Description) The data scientists at BigMart have collected 2013 sales data for 1559 products across 10 stores in…

Android控制ScrollView滑動速度

翻閱查找ScrollView的文檔并搜索了一下沒有發現直接設置的屬性和方法&#xff0c;這里通過繼承來達到這一目的。 /*** 快/慢滑動ScrollView * author農民伯伯 * */public class SlowScrollView extends ScrollView {public SlowScrollView(Context context, Att…

數據特征分析-帕累托分析

帕累托分析(貢獻度分析)&#xff1a;即二八定律 目的&#xff1a;通過二八原則尋找屬于20%的關鍵決定性因素。 隨機生成數據 df pd.DataFrame(np.random.randn(10)*10003000,index list(ABCDEFGHIJ),columns [銷量]) #避免出現負數 df.sort_values(銷量,ascending False,i…

leetcode 304. 二維區域和檢索 - 矩陣不可變(前綴和)

給定一個二維矩陣&#xff0c;計算其子矩形范圍內元素的總和&#xff0c;該子矩陣的左上角為 (row1, col1) &#xff0c;右下角為 (row2, col2) 。 上圖子矩陣左上角 (row1, col1) (2, 1) &#xff0c;右下角(row2, col2) (4, 3)&#xff0c;該子矩形內元素的總和為 8。 示…