Spring注入的一些特点

2019-04-23  本文已影响0人  setone

了解一下spring注入的一些规则

@Configuration
public class BeanConfig {
        @Bean
    public Budget budget(){
        Budget budget = new  Budget();
        budget.setCompany("牛逼科技");
        return budget;
    } 
    
    @Bean(name="budget1")
    public Budget budget23(){
        Budget budget = new  Budget();
        budget.setCompany("牛逼科技");
        return budget;
    } 
    
    @Bean
    public Budget budget2(){
        Budget budget = new  Budget();
        budget.setCompany("牛逼科技123123");
        return budget;
    } 

这两个bena的注入写法是

    @Autowired
    Budget budget;
    
    @Autowired
    @Qualifier("budget2")
    Budget budget2;
    
    @Autowired
    @Qualifier("budget1")
    Budget budget1;

@Bean注解里面有个name字段,如果你申明了,那么bean的name会按照你申明的注入,没有声明会按照默认的名称(方法名类名首字母小写)注入

        localSessionFactoryBean.setPackagesToScan("com.cmcmc");
        
        ApplicationContext applicationContext = SpringContextAware.getApplicationContext();
        DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory)applicationContext.getAutowireCapableBeanFactory();
        beanFactory.applyBeanPostProcessorsAfterInitialization(localSessionFactoryBean, localSessionFactoryBean.getClass().getName());
        beanFactory.registerSingleton(localSessionFactoryBean.getClass().getName(), localSessionFactoryBean);
image.png

如图我们实现了动态修改bean

上一篇下一篇

猜你喜欢

热点阅读