国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發(fā)設計 > 正文

干貨:淺談Spring框架注解的用法分析

2019-11-11 02:01:50
字體:
來源:轉載
供稿:網友

干貨:淺談Spring框架注解的用法分析

眾所周知,在javaEE開發(fā)框架中,SPRing框架是用的最多的,注解在框架的定位也就越來越明顯了。說句玩笑話:能用一個注解解決的,絕不用一堆配置和代碼解決;如果不能解決,那么來兩個注解;


1.@Component是Spring定義的一個通用注解,可以注解任何bean。

2.@Scope定義bean的作用域,其默認作用域是"singleton",除此之外還有prototype,request,session和global session。


案例:@Component和@Scope用法分析:

BeanAnnotation類:

@Scope
@Component
public class BeanAnnotation { 
	public void say(String arg) { 
		System.out.println("BeanAnnotation : " + arg); 
	public void myHashCode() { 
		System.out.println("BeanAnnotation : " + this.hashCode()); 
	}
}

junit4測試類→TestBeanAnnotation類:

@RunWith(BlockJUnit4ClassRunner.class)
public class TestBeanAnnotation extends UnitTestBase {
	 public TestBeanAnnotation() { 
		super("classpath*:spring-beanannotation.xml"); 
	}
	 @Test
	public void testSay() {
		 BeanAnnotation bean = super.getBean("beanAnnotation"); 
		bean.say("This is test.");
	 }
 	@Test 
	public void testScpoe() {
		 BeanAnnotation bean = super.getBean("beanAnnotation");
	 	bean.myHashCode(); 
		bean = super.getBean("beanAnnotation"); bean.myHashCode(); 
	}
}

Spring配置文件→spring-beanannotation.xml:

<context:component-scan base-package="com.beanannotation"></context:component-scan>

我們先從Spring配置文件分析,base-package="com.beanannotation"說明我們只處理這個包名下面的注解。

然后分析BeanAnnotation類,有一個say的方法。假設我們不清楚這是一個什么類型(注:Service或者DAO)的類,我們可以用一個通用的注解@Component。

最后分析TestBeanAnnotation類,testSay方法里super.getBean("beanAnnotation")是從IOC的容器中取到這個bean,并調用bean的say方法。

提出問題的時間到了,當我們super.getBean的時候是通過bean的id從IOC容器中獲取的,那么這個id是什么呢?因為在我們添加@Component到BeanAnnotation類上的時候,默認的id為beanAnnotation。如果指定了@Component的名稱,譬如指定為@Component(”bean”)的時候,在單元測試的時候就必須把super.getBean得到的id與之相對應才能測試成功。

在這里我把@Scope注解單獨分離出來分析,在TestBeanAnnotation類里面有一個testScpoe方法。在BeanAnnotation類里面有一個myHashCode方法,可能大家有些疑惑,為什么要用this.hashCode()?因為@Scope指定的是bean的作用域,為了保證測試類的結果準確明了,所以采用哈希碼值來判斷是否為同一個對象。


3.@Repository、@Service、@Controller是更具有針對性的注解。

PS:這里我們需要明白這三個注解是基于@Component定義的注解哦:

①、@Repository通常用于注解DAO類,也就是我們常說的持久層。

②、@Service通常用于注解Service類,也就是服務層。

③、@Controller通常用于Controller類,也就是控制層(MVC)。

4.@Autowired理解為“傳統(tǒng)”的setter方法,可以用在setter方法上,也可以用在構造器或者成員變量,能夠進行Spring Bean的自動裝配。


案例:@Autowired用法分析一:

Spring配置文件→spring-beanannotation.xml:

<context:component-scan base-package="com.beanannotation"></context:component-scan>

SimpleMovieLister類:

public class SimpleMovieLister {
	 private MovieFinder movieFinder;
 	@Autowired(required=false)
	public void setMovieFinder(MovieFinder movieFinder) {
		 this.movieFinder = movieFinder; 
	}
}

在默認的情況下,如果找不到合適的bean將會導致autowiring失敗拋出異常,我們可以將@Autowired注解在這個set方法上,標記required=false來避免。但是,這不是一個必須的,如果找不到movieFinder的實例,是不會拋出異常的,只有在使用的時候發(fā)現movieFinder為null,在這種情況下,就要求我們在使用的時候,首先判斷movieFinder是不是為null,如果是就會報空指針異常 。

值得注意的是,我們知道每個類可以有很多個構造器,但是在使用@Autowired的時候,有且只能有一個構造器能夠被標記為required=true(注:required的默認值為false)。


案例:@Autowired用法分析二:

BeanImplOne類:

@Order
@Component
public class BeanImplOne implements BeanInterface {}

BeanImplTwo類:

@Order
@Component
public class BeanImplTwo implements BeanInterface {}

BeanInterface類:

public interface BeanInterface {}

BeanInvoker類:

@Component
public class BeanInvoker {
	 @Autowired 
	private List<BeanInterface> list;
	 @Autowired 
	private Map<String, BeanInterface> map; 
	public void say() {
		 if (null != list && 0 != list.size()) {
			 for (BeanInterface bean : list) {
			 System.out.println(bean.getClass().getName()); 
			}
		 } else { 
			System.out.println(" list is null !"); 
		}
		if (null != map && 0 != map.size()) {
			 for (Map.Entry<String, BeanInterface> entry : 
			map.entrySet()) { 
				System.out.println(entry.getKey() + " " + entry.getValue().getClass().getName()); 
		} else {
		 System.out.println("map is null !"); 
	}
}

測試類TestInjection:

@RunWith(BlockJUnit4ClassRunner.class)
public class TestInjection extends UnitTestBase {
	public TestInjection() {
		super("classpath:spring-beanannotation.xml"); 
	@Test 
	public void testMultiBean() { 
		BeanInvoker invoker = super.getBean("beanInvoker"); 
		invoker.say(); 
	}
}

首先,我們清楚BeanImplOne類和BeanImplTwo類是實現了BeanInterface接口的,在BeanInvoker類里面我們定義了list和map,我們通過@Autowired注解把BeanImplOne類和BeanImplTwo類注解進入其中。那么怎么證實是@Autowired注解把這兩個類注入到list或者map中的呢?那么請看if循環(huán)語句和foreach循環(huán)打印,通過這個邏輯判斷,如果能夠打印出BeanImplOne類和BeanImplTwo類的路徑名,就說明這樣是可以的。如果有些小伙伴可能不信,那么可以試著不使用@Autowired注解,看結果怎么樣。

測試類沒有什么好說的,各位小伙伴有沒有注意到@Order注解呢?這里需要解釋的就是,如果在@Order注解里面輸入執(zhí)行的數字,比如1或者2,那么打印出來的路徑名就會按順序,也就是說通過指定@Order注解的內容可以實現優(yōu)先級的功能。


5.@ImportResource注解引入一個資源,對應一個xml文件

6.@Value注解從資源文件中,取出它的key并賦值給當前類的成員變量


案例:@ImportResource和@Value用法分析:

MyDriverManager類:

public class MyDriverManager { 
	public MyDriverManager(String url, String userName, String passWord) {
		 System.out.println("url : " + url);
		 System.out.println("userName: " + userName);
		 System.out.println("password: " + password); 
	}
}

config.xml:

<context:property-placeholder location="classpath:/config.properties"/>

StoreConfig類:

@Configuration
@ImportResource("classpath:config.xml")
public class StoreConfig { 
	@Value("${jdbc.url}") 
	private String url; 
	@Value("${jdbc.username}") 
	private String username; 
	@Value("${jdbc.password}") 
	private String password; 
	@Bean public MyDriverManager myDriverManager() {
		 return new MyDriverManager(url, username, password); 
	}

這個案例我們使用注解配置jdbc數據庫的連接,首先創(chuàng)建一個內含構造器的MyDriverManager類,然后配置config.xml里面的資源文件路徑,以便@ImportResource注解獲取,最后配置StoreConfig類。(注意url、username、password也必須要和數據庫的保持一致哦)

詳解StoreConfig類:

首先我們定義三個成員變量,然后給每一個成員變量打上一個@value注解,注意@value里面的內容一定是資源文件里面的key值。這里的@ImportResource注解就是指明一個資源文件,在這個資源文件里面獲取到對應的數據。

那么@Configuration注解是用來干嘛的呢?為什么不用@Component注解呢?其實是這樣的,@Component注解用于將所標注的類加載到 Spring 環(huán)境中,這時候是需要配置component-scan才能使用的,而@Configuration注解是Spring 3.X后提供的注解,它用于取代XML來配置 Spring。


7.@Bean注解用來標識配置和初始化一個由SpringIOC容器管理的新對象的方法,類似XML中配置文件的<bean/>

ps:默認的@Bean注解是單例的,那么有什么方式可以指定它的范圍呢?所以這里才出現了@Scope注解

8.@Scope注解,在@Scope注解里面value的范圍和Bean的作用域是通用的,proxyMode的屬性是采用哪一種的單例方式(一種是基于接口的注解,一種是基于類的代理)


案例:@Bean和@Scope用法分析:

@Bean 
@Scope(value ="session",proxyMode = "scopedProxyMode.TARGET_CLASS") 
public UserPreferences userPreferences(){
	return new userPreferences(); 
@Bean 
public service userService(){ 
	UserService service =new SimpleUserService();
	service.setUserPreferences(userPreferences);
	return service; 
}

本文轉自簡書,侵權聯系小編刪除


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 凌源市| 平江县| 简阳市| 霍邱县| 沅江市| 曲水县| 龙海市| 胶州市| 江津市| 叶城县| 寿阳县| 宁武县| 杭锦旗| 康保县| 延川县| 柞水县| 炉霍县| 绥芬河市| 博客| 湖南省| 德州市| 石门县| 广河县| 于都县| 类乌齐县| 大宁县| 博客| 江油市| 工布江达县| 栾城县| 阳泉市| 金坛市| 藁城市| 丰都县| 长葛市| 三河市| 东阿县| 德阳市| 泸定县| 鲁山县| 乐业县|