spring文档阅读笔记(三)

1.@Required

注释在set方法上 这个注释仅仅表明,受影响的bean属性必须在配置时被填充,通过一个bean定义中的显式属性值或通过自动连接来填充。

@Required
    public void setMovieFinder(MovieFinder movieFinder) {
        this.movieFinder = movieFinder;
    }

2.@Autowired

可以用于构造器、用于属性、用于set方法,表示根据类型自动填充

package com.tutorialspoint;
import org.springframework.beans.factory.annotation.Autowired;
public class TextEditor {
   private SpellChecker spellChecker;
   @Autowired
   public TextEditor(SpellChecker spellChecker){
      System.out.println("Inside TextEditor constructor." );
      this.spellChecker = spellChecker;
   }
   public void spellCheck(){
      spellChecker.checkSpelling();
   }
}

required=false表示不需要在配置使其必须填充

@Autowired(required=false)
   public void setAge(Integer age) {
      this.age = age;
   }  

@Autowired还可以自动注入BeanFactory, ApplicationContext, Environment, ResourceLoader, ApplicationEventPublisher

public class MovieRecommender {

    @Autowired
    private ApplicationContext context;

    public MovieRecommender() {
    	
    }
    
    public void fun(){
    	TestBean test = (TestBean) context.getBean("testBean");
    	test.fun();
    }

}

3.srping的@Autowired, @Inject, @Resource, @Value这些注解都是通过BeanPostProcessor来处理的

4.@Configuration与@bean

@Configuration
public class AppConfig {

    @Bean
    public TransferService transferService() {
        return new TransferServiceImpl();
    }

}
这个配置就等同于之前在xml里的配置

<beans>
    <bean id="transferService" class="com.acme.TransferServiceImpl"/>
</beans>

5.@Primary

如果通过@AutoWried根据类型自动装配配置,在多个候选人中的某个配置了@primary,那么这个候选人将会被优先装载

@Configuration
public class MovieConfiguration {

    @Bean
    @Primary
    public MovieCatalog firstMovieCatalog() { ... }

    @Bean
    public MovieCatalog secondMovieCatalog() { ... }

}

or

<bean class="example.SimpleMovieCatalog" primary="true">
        <!-- inject any dependencies required by this bean -->
    </bean>

6.@Autowired+@qulifer可以根据类型+名称装配

public class MovieRecommender {

    @Autowired
    @Qualifier("main")
    private MovieCatalog movieCatalog;

    // ...
}

也可以放入构造器当中

@Autowired
    public void prepare(@Qualifier("main")MovieCatalog movieCatalog,
            CustomerPreferenceDao customerPreferenceDao) {
        this.movieCatalog = movieCatalog;
        this.customerPreferenceDao = customerPreferenceDao;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值