2.springboot(@ImportResource的用法)

@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;
    }

}
创建测试方法:

测试结果

当使用@ImportResource导入两个以上的配置文件时,外边加上大括号,中间用逗号隔开

 

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

做一道光

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值