@Autowired 与@Resource
- @Autowired是spring自己定义的注解,@Resource是JAVA规范JSR-250的注解,为spring所支持
- @Resource的作用相当于@Autowired,都可以用来装配bean,都可以写在字段或setter方法上。只不过@Autowired按byType自动注入,而@Resource默认按 byName自动注入
- 都可修饰变量、setter方法,只Resource可修饰构造方法
@Inject、@Named
- JSR-330注解,默认按byType注入,如果按byName注入的话,需要配合@Named使用
- 可修饰变量、setter方法、构造方法(同Autowired)
import javax.inject.Inject;
import javax.inject.Named;
@Named("movieListener") // @ManagedBean("movieListener") could be used as well
public class SimpleMovieLister {
private MovieFinder movieFinder;
@Inject
public void setMovieFinder(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}
}
@Component、@Service、@Repository、@Controller、@Configuration、@Bean
- 以上每个注解都会实例化一个AnnotationConfigApplicationContext
- @Configuration(类级别的注解)使用Configuration修饰的类内部可以定义“内部bean”(@bean修饰的方法)
- @Bean(方法级的注解)修饰的方法内部不可再定义“内部Bean”
- 经常可以先用Configuration修饰整个class,然后在内部使用@Bean修饰方法,提供更精细化的注入策略
@Configuration
public class AppConfig {
@Bean
public TransferServiceImpl transferService() {
return new TransferServiceImpl();
}
}
@ComponentScan、@Scope
- @ComponentScan:确保引用的组件能够被扫描到
- @Scope用于确定bean的作用域,默认是单例,即scope=“singleton”。还有prototype、request、session等。
@Required
- 修饰Bean的setter方法,用于检查一个Bean的属性的值在配置期间是否被初始化,如果没有,在引用该bean时会抛出BeanInitializationException
@Import
- 在应用中,有时没有把某个类注入到IOC容器,但使用时需要获取该类的bean,此时需要用到@Import。
@Bean(initMethod="")、@Bean(destroyMethod="")
- 默认情况下一个bean有自己的出初始化和终结方法,如果想自定义,可以使用以上两种样式
@Profile
- 用来标明当前运行环境
- 在spring使用DI来依赖注入的时候,能够根据当前制定的运行环境来注入相应的bean。最常见的就是使用不同的DataSource
- 环境设置:-Dspring.profiles.active=“dev”
@Configuration
@Profile(value = "dev")
@Component
public class Chinese implements MoveFactor {
@Override
public void speak() {
System.out.println("hello");
}
}
@PropertySource
- 通过@PropertySource注解将properties配置文件中的值存储到Spring的 Environment中,Environment接口提供方法去读取配置文件中的值,参数是properties文件中定义的key值。
@Configuration
@PropertySource("classpath:/com/myco/app.properties")
public class PropertiesWithJavaConfig {
@Value(${jdbc.driver})
private String driver;
@Value(${jdbc.url})
private String url;
}
@Configuration
@PropertySource("classpath:/com/${my:default/path}/app.properties")
public class AppConfig {
@Autowired
Environment env;
@Bean
public TestBean testBean() {
TestBean testBean = new TestBean();
testBean.setName(env.getProperty("testbean.name"));
return testBean;
}
}
@Async
- 基于@Async标注的方法,称之为异步方法;这些方法将在执行的时候,将会在独立的线程中被执行,调用者无需等待它的完成,即可继续其他的操作。
- 启用该注解:@EnableAsync
- 使用:直接把注解加到方法上即可
- 在异步方法中,如果出现异常,对于调用者caller而言,是无法感知的。