Customer:
package com.baizhiedu.bean;
import org.springframework.stereotype.Component;
@Component //通过注解创建他的对象
public class Customer {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
applicationContext.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">
<!-- 配置文件会覆盖@Bean注解-->
<bean id="customer" class="com.baizhiedu.bean.Customer">
<property name="id" value="2"/>
<property name="name" value="xiaohuahua"/>
</bean>
</beans>
AppConfig:
package com.baizhiedu;
import com.baizhiedu.bean.Customer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
@Configuration //配置Bean注解类,里面写@Bean,来创建对象
@ComponentScan(basePackages = "com.baizhiedu.bean") //注解扫描
@ImportResource("applicationContext.xml") //用注解让 配置文件与配置Bean继承,会先读取配置Bean,再根据上面的配置把上面的配置把配置文件整合起来
public class AppConfig3 {
//进行覆盖@Configuration
@Bean
public Customer customer(){
Customer customer=new Customer();
customer.setId(1);
customer.setName("xiaojianren");
return customer;
}
}
TestAnnotation2:
package com.baizhiedu;
import com.baizhiedu.bean.Customer;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class TestAnnotation2 {
//用于测试:@componentScan 扫描基础注解的使用
@Test
public void test1(){
ApplicationContext ctx=new AnnotationConfigApplicationContext(AppConfig2.class);
String[] beanDefinitionNames=ctx.getBeanDefinitionNames();//获取所有对象的id
for (String beanDefinitionName:beanDefinitionNames){
System.out.println("beanDefinitionName="+beanDefinitionName);
}
}
//用于测试:测试创建对象的优先级: @Component及其衍生注解<@Bean<配置文件bean标签
//高优先级会覆盖低优先级
@Test
public void test3(){
ApplicationContext ctx=new AnnotationConfigApplicationContext(AppConfig3.class);
Customer customer=(Customer) ctx.getBean("customer");
System.out.println("cus="+customer.getId());
System.out.println("cus="+customer.getName());
}
}
当没有写@Bean和@ImportResources时,@Component创建的对象的属性为空值:
加入@Bean注解,覆盖@Component注解:
@ImportResources引入配置文件,覆盖@Bean注解: