在实际开发中可能既要有配置文件存在,也要使用java配置的方式,这时候就需要使用@ImportResource注解来实现了
UserBean类
package com.zhouym.condition;
public class UserBean {
private int id;
private String name;
private int age;
public UserBean() {
super();
}
public UserBean(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "UserBean [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
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"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
<bean class="com.zhouym.condition.UserBean"/>
</beans>
java配置文件
package com.zhouym.condition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
@Configuration
@ImportResource("classpath:applicationContext.xml")
public class AppConfig {
@Bean
public Book book() {
return new Book();
}
}
测试类
package com.zhouym.condition;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class BlendTest {
public static void main(String[] args) {
AnnotationConfigApplicationContext acac =
new AnnotationConfigApplicationContext(AppConfig.class);
UserBean ub = acac.getBean(UserBean.class);
System.out.println(ub);
System.out.println("------------");
Book book = acac.getBean(Book.class);
System.out.println(book);
}
}
测试结果