@Confguration->告訴spring這是一個(gè)配置類
以前我們是使用配置文件來(lái)注冊(cè)bean的,現(xiàn)如今可以用@Configuration
來(lái)代替配置文件。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-667455.html
//配置配==配置文件
@Configuration // 告訴Spring這是一個(gè)配置類,等同于以前的配置文件
public class MainConfig {
// @Bean注解是給IOC容器中注冊(cè)一個(gè)bean,id默認(rèn)是用方法名作為id,類型自然就是返回值的類型
@Bean
public Person person() {
return new Person("liayun", 20);
}
}
如何通過(guò)注解配置類來(lái)獲取ioc容器和bean呢?
public class MainTest {
public static void main(String[] args) {
// ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml"); 以前我們是通過(guò)配置文件的路徑來(lái)獲取Ioc容器,現(xiàn)在我們是基于注解開發(fā),不用ClassPathXmlApplicationContext了
// Person person = (Person) applicationContext.getBean("person");
// System.out.println(person);
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class /*這里存放的是配置類的class對(duì)象*/); //獲取ioc容器
Person person = applicationContext.getBean(Person.class); //獲取ioc容器里面的組件,也就是Bean對(duì)象
System.out.println(person);
// Person這個(gè)類型的組件在IOC容器中的名字是什么呢?
String[] namesForType = applicationContext.getBeanNamesForType(Person.class);
for (String name : namesForType) {
System.out.println(name);
}
}
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-667455.html
到了這里,關(guān)于使用@Configuration和@Bean給spring容器中注入組件的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!