Spring的@Bean和@Autowired組合使用詳解
@Bean 基礎(chǔ)概念
- @Bean:Spring的@Bean注解用于告訴方法,產(chǎn)生一個Bean對象,然后這個Bean對象交給Spring管理。產(chǎn)生這個Bean對象的方法Spring只會調(diào)用一次,隨后這個Spring將會將這個Bean對象放在自己的IOC容器中;
- SpringIOC 容器管理一個或者多個bean,這些bean都需要在@Configuration注解下進(jìn)行創(chuàng)建,在一個方法上使用@Bean注解就表明這個方法需要交給Spring進(jìn)行管理;
- @Bean是一個方法級別上的注解,主要用在@Configuration注解的類里,也可以用在@Component注解的類里。添加的bean的id為方法名;
- 使用Bean時(shí),即是把已經(jīng)在xml文件中配置好的Bean拿來用,完成屬性、方法的組裝;比如@Autowired , @Resource,可以通過byTYPE(@Autowired)、byNAME(@Resource)的方式獲取Bean;
- 注冊Bean時(shí),@Component , @Repository , @ Controller , @Service , @Configration這些注解都是把你要實(shí)例化的對象轉(zhuǎn)化成一個Bean,放在IoC容器中,等你要用的時(shí)候,它會和上面的@Autowired , @Resource配合到一起,把對象、屬性、方法完美組裝;
@Autowired 基礎(chǔ)概念
@Autowired 可以將spring ioc 中的bean(例如@Bean 注解創(chuàng)建的bean)的實(shí)例獲取。
舉個例子
一,使用@Bean 在某個方法上,產(chǎn)生一個bean 對象
@Configuration
public class TokenConfig {
/**
* @Bean 注解是告訴該方法產(chǎn)生一個bean 對象,然后將該對象交給spring管理,產(chǎn)生這個bean 對象的方法spring 只會調(diào)用一次。隨后spring會將這個bean對象放在自己的ioc容器中。
*/
@Bean
public TokenStore tokenStore() {
//JWT令牌存儲方案
return new JwtTokenStore();
}
}二,使用@Autowired注解,將在spring 中的bean 對象獲取到TokenStore
@Configuration
@EnableAuthorizationServer
public class AuthorizationServer extends AuthorizationServerConfigurerAdapter {
@Autowired
private TokenStore tokenStore;
public AuthorizationServerTokenServices tokenService() {
DefaultTokenServices service=new DefaultTokenServices();
//客戶端詳情服務(wù)
service.setClientDetailsService(clientDetailsService);
//支持刷新令牌
service.setSupportRefreshToken(true);
//令牌存儲策略
service.setTokenStore(tokenStore);//這一行的tokenStore
//令牌增強(qiáng)
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
tokenEnhancerChain.setTokenEnhancers(Arrays.asList(accessTokenConverter));
service.setTokenEnhancer(tokenEnhancerChain);
// 令牌默認(rèn)有效期2小時(shí)
service.setAccessTokenValiditySeconds(7200);
// 刷新令牌默認(rèn)有效期3天
service.setRefreshTokenValiditySeconds(259200);
return service;
}
}service.setTokenStore(tokenStore);//這一行的tokenStore的意思和
service.setTokenStore(new JwtTokenStore); 是一樣的。
使用 @Autowired 引入TokenStore 類就可以獲取我們使用@Bean對該對象設(shè)置的實(shí)例了。
注意,不用管TokenStore 是 interface還是class.都可以被@Bean 調(diào)用
到此這篇關(guān)于Spring的@Bean和@Autowired組合使用詳解的文章就介紹到這了,更多相關(guān)@Bean和@Autowired組合使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
springboot返回modelandview頁面的實(shí)例
這篇文章主要介紹了springboot返回modelandview頁面的實(shí)例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-10-10
Maven+Tomcat8 實(shí)現(xiàn)自動化部署的方法
本篇文章主要介紹了Maven+Tomcat8 實(shí)現(xiàn)自動化部署的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-10-10
關(guān)于springboot響應(yīng)式編程整合webFlux的問題
在springboot2.x版本中提供了webFlux依賴模塊,該模塊有兩種模型實(shí)現(xiàn):一種是基于功能性端點(diǎn)的方式,另一種是基于SpringMVC注解方式,今天通過本文給大家介紹springboot響應(yīng)式編程整合webFlux的問題,感興趣的朋友一起看看吧2022-01-01
springboot實(shí)現(xiàn)防重復(fù)提交和防重復(fù)點(diǎn)擊的示例
這篇文章主要介紹了springboot實(shí)現(xiàn)防重復(fù)提交和防重復(fù)點(diǎn)擊的示例,幫助大家更好的理解和學(xué)習(xí)springboot框架,感興趣的朋友可以了解下2020-09-09

