非注入方式获取Spring Bean
- 使用ApplicationContext.getBean(Class
clazz)方法获取Bean实例,如下所示:
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
MyBean myBean = context.getBean(MyBean.class);
- 使用ApplicationContext.getBean(String name, Class
clazz)方法获取Bean实例,如下所示:
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
MyBean myBean = context.getBean("myBean", MyBean.class);
- 使用@Autowired注解自动注入Bean实例,需要将类标记为@Component或@Service等注解,如下所示:
@Component
public class MyComponent {
@Autowired
private MyBean myBean;
//...
}
- 使用@Resource注解自动注入Bean实例,需要将类标记为@Component或@Service等注解,如下所示:
@Component
public class MyComponent {
@Resource
private MyBean myBean;
//...
}
注意:@Autowired和@Resource注解可以用在属性、构造方法和Setter方法上。如果有多个同类型的Bean实例,可以使用@Qualifier注解指定具体的Bean实例
原文地址: https://www.cveoy.top/t/topic/eOtQ 著作权归作者所有。请勿转载和采集!