@ImportResource 是导入 xml 配置,等同于 xml 文件的 resources
创建数据类Cat
package com.it.springboot.entity;
public class Cat {
private String cardId;
private String name;
private Integer age;
@Override
public String toString() {
return "Cat{" +
"cardId='" + cardId + '\'' +
", name='" + name + '\'' +
", age=" + age +
'}';
}
public String getCardId() {
return cardId;
}
public void setCardId(String cardId) {
this.cardId = cardId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="myCat" class="com.it.springboot.entity.Cat">
<property name="cardId" value="001"/>
<property name="name" value="tom猫"/>
<property name="age" value="2"/>
</bean>
</beans>
创建配置类:
JavaConfig
package com.it.springboot.config;
import com.it.springboot.entity.Student;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
/**
* Configuration:表示当前类作为配置文件使用的,就是配置容器的。
* 位置:在类的上面
* SpringConfig这个类就相当于beans.xml
*/
@Configuration
@ImportResource(value = "classpath:applicationContext.xml")
public class SpringConfig {
/**
* 创建方法,方法的返回值是对象。在方法的上面加入@bean
* 方法的返回值对象就注入到容器中。
*
* @Bean:把对象注入到spring容器中,作用相当于<bean></bean>
* 位置:方法的上面
*
* 说明:@Bean,不指定对象的名称,默认是方法名的id
*/
@Bean
public Student createStudent(){
Student s1=new Student();
s1.setName("李四");
s1.setAge(19);
s1.setSex("女");
return s1;
}
/**
* 指定对象在容器中的名字
* @return
*/
@Bean(name = "lisiStudent")
public Student makeStudent(){
Student s2=new Student();
s2.setName("小红");
s2.setAge(22);
s2.setSex("女");
return s2;
}
}
创建测试方法:
![](https://i-blog.csdnimg.cn/blog_migrate/4ca8bc1386135a08b07ef96fa39e4d19.png)
测试结果
当使用@ImportResource导入两个以上的配置文件时,外边加上大括号,中间用逗号隔开