1 @Configuration
作用:辨別該類為spring的一個配置類。
執行個體:
@Configuration
public class ConfigTest {
@Bean
public Person person() {
return new Person("haha", 100);
}
}
源碼:
@Component
public @interface Configuration {
String value() default "";
}
了解:相當于依靠配置檔案時的bean.xml檔案.
在通過配置檔案向IOC容器中加入bean的時候,需要建立一個xml檔案,然後在XML檔案中通過<bean>标簽
向IOC在容器中注冊bean
在這裡:@Configuration《====》bean.xml檔案
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<beans>
<bean id="person" class="com.rayli.beans.Person">
<property name="age" value="123"></property>
<property name="name" value="rayli"></property>
</bean>
</beans>
</beans>
2 @Bean注解
作用:向IOC容器中注冊bean. @Bean《====》<bean>标簽
執行個體:是方法級别的。
傳回類型《====》<bean>标簽中的class屬性
方法名《====》<bean>标簽中的id屬性
@Bean
public Person person() {
return new Person("haha", 100);
}
PS 在IOC容器中存在的bean的名字,就是配置類中方法名。
需要修改的話:
方法一:修改方法名。
方法二:@Bean有參數 name 和value都可以用來修改這個bean在IOC容器彙中的名稱。
@Bean(value="person01") @Bean(name="person01")
3 在IOC容器中擷取通過配置類配置的bean
public class TestMain {
public static void main(String[] args) {
//擷取IOC容器 AnnotationConfigApplicationContext(配置類)
ApplicationContext app = new AnnotationConfigApplicationContext(ConfigTest.class);
//通過類型擷取
Person person1 = app.getBean(Person.class);
System.out.println(person1);
//通過id擷取
Person person2 = (Person) app.getBean("person");
System.out.println(person2);
}
}