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

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

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

2019-11-11 00:39:40
字體:
供稿:網(wǎng)友

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

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


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

2.@Scope定義bean的作用域,其默認(rèn)作用域是"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"說明我們只處理這個(gè)包名下面的注解。

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

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

提出問題的時(shí)間到了,當(dāng)我們super.getBean的時(shí)候是通過bean的id從IOC容器中獲取的,那么這個(gè)id是什么呢?因?yàn)樵谖覀兲砑覢Component到BeanAnnotation類上的時(shí)候,默認(rèn)的id為beanAnnotation。如果指定了@Component的名稱,譬如指定為@Component(”bean”)的時(shí)候,在單元測試的時(shí)候就必須把super.getBean得到的id與之相對應(yīng)才能測試成功。

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


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

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

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

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

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

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


案例:@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; 
	}
}

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

值得注意的是,我們知道每個(gè)類可以有很多個(gè)構(gòu)造器,但是在使用@Autowired的時(shí)候,有且只能有一個(gè)構(gòu)造器能夠被標(biāo)記為required=true(注:required的默認(rèn)值為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類是實(shí)現(xiàn)了BeanInterface接口的,在BeanInvoker類里面我們定義了list和map,我們通過@Autowired注解把BeanImplOne類和BeanImplTwo類注解進(jìn)入其中。那么怎么證實(shí)是@Autowired注解把這兩個(gè)類注入到list或者map中的呢?那么請看if循環(huán)語句和foreach循環(huán)打印,通過這個(gè)邏輯判斷,如果能夠打印出BeanImplOne類和BeanImplTwo類的路徑名,就說明這樣是可以的。如果有些小伙伴可能不信,那么可以試著不使用@Autowired注解,看結(jié)果怎么樣。

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


5.@ImportResource注解引入一個(gè)資源,對應(yīng)一個(gè)xml文件

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


案例:@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); 
	}

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

詳解StoreConfig類:

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

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


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

ps:默認(rèn)的@Bean注解是單例的,那么有什么方式可以指定它的范圍呢?所以這里才出現(xiàn)了@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; 
}

本文轉(zhuǎn)自簡書,侵權(quán)聯(lián)系小編刪除


發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 香河县| 巴里| 贵南县| 舟曲县| 嘉鱼县| 巧家县| 巴东县| 巫溪县| 孝昌县| 于田县| 云和县| 晋城| 财经| 宾川县| 临城县| 大关县| 隆化县| 璧山县| 昌都县| 河池市| 桐城市| 漾濞| 涡阳县| 宁乡县| 望都县| 大同县| 余江县| 三江| 毕节市| 华亭县| 资兴市| 宝清县| 达孜县| 卓尼县| 内乡县| 城固县| 易门县| 黔江区| 荥阳市| 定州市| 新建县|