Spring獲取Bean有以下幾種方式:
@Component
public class MyClass {
@Autowired
private MyBean myBean;
//...
}
@Configuration
public class AppConfig {
@Bean
public MyBean myBean() {
return new MyBean();
}
//...
}
@Component
public class MyClass {
@Autowired
private MyBean myBean;
//...
}
@Configuration
public class AppConfig1 {
@Bean
public MyBean myBean1() {
return new MyBean();
}
//...
}
@Configuration
public class AppConfig2 {
@Bean
public MyBean myBean2() {
return new MyBean();
}
//...
}
@Component
@Import({AppConfig1.class, AppConfig2.class})
public class MyClass {
@Autowired
private MyBean myBean1;
@Autowired
private MyBean myBean2;
//...
}
@Configuration
@ImportResource({"classpath:applicationContext.xml"})
public class AppConfig {
//...
}
@Component
public class MyClass {
@Autowired
private MyBean myBean;
//...
}
@Component
public class MyClass {
private MyBean myBean;
@Autowired
private ApplicationContext applicationContext;
@PostConstruct
public void init() {
myBean = applicationContext.getBean(MyBean.class);
}
//...
}