@Bean:Spring的@Bean注解用于告诉方法,产生一个Bean对象,然后这个Bean对象交给Spring管理。产生这个Bean对象的方法Spring只会调用一次,随后这个Spring将会将这个Bean对象放在自己的IOC容器中;
SpringIOC 容器管理一个或者多个bean,这些bean都需要在@Configuration注解下进行创建,在一个方法上使用@Bean注解就表明这个方法需要交给Spring进行管理;
@Bean是一个方法级别上的注解,主要用在@Configuration注解的类里,也可以用在@Component注解的类里。添加的bean的id为方法名;
使用Bean时,即是把已经在xml文件中配置好的Bean拿来用,完成属性、方法的组装;比如@Autowired , @Resource,可以通过byTYPE(@Autowired)、byNAME(@Resource)的方式获取Bean;
注册Bean时,@Component , @Repository , @ Controller , @Service , @Configration这些注解都是把你要实例化的对象转化成一个Bean,放在IoC容器中,等你要用的时候,它会和上面的@Autowired , @Resource配合到一起,把对象、属性、方法完美组装;
@Autowired 可以将spring ioc 中的bean(例如@Bean 注解创建的bean)的实例获取。
@Configuration
public class TokenConfig {/*** @Bean 注解是告诉该方法产生一个bean 对象,然后将该对象交给spring管理,产生这个bean 对象的方法spring 只会调用一次。随后spring会将这个bean对象放在自己的ioc容器中。*/@Beanpublic TokenStore tokenStore() {//JWT令牌存储方案return new JwtTokenStore();}
}
@Configuration
@EnableAuthorizationServer
public class AuthorizationServer extends AuthorizationServerConfigurerAdapter {@Autowiredprivate TokenStore tokenStore;public AuthorizationServerTokenServices tokenService() {DefaultTokenServices service=new DefaultTokenServices();//客户端详情服务service.setClientDetailsService(clientDetailsService);//支持刷新令牌service.setSupportRefreshToken(true);//令牌存储策略service.setTokenStore(tokenStore);//这一行的tokenStore//令牌增强TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();tokenEnhancerChain.setTokenEnhancers(Arrays.asList(accessTokenConverter));service.setTokenEnhancer(tokenEnhancerChain);// 令牌默认有效期2小时service.setAccessTokenValiditySeconds(7200);// 刷新令牌默认有效期3天service.setRefreshTokenValiditySeconds(259200);return service;}
}
service.setTokenStore(tokenStore);//这一行的tokenStore的意思和
service.setTokenStore(new JwtTokenStore); 是一样的。
使用 @Autowired 引入TokenStore 类就可以获取我们使用@Bean对该对象设置的实例了。
注意,不用管TokenStore 是 interface还是class.都可以被@Bean 调用