侧边栏壁纸
博主头像
张种恩的技术小栈博主等级

行动起来,活在当下

  • 累计撰写 743 篇文章
  • 累计创建 64 个标签
  • 累计收到 39 条评论

目 录CONTENT

文章目录

SpringBoot(6)之加载Spring配置文件

zze
zze
2018-01-19 / 0 评论 / 0 点赞 / 471 阅读 / 2093 字

不定期更新相关视频,抖音点击左上角加号后扫一扫右方侧边栏二维码关注我~正在更新《Shell其实很简单》系列

@PropertySource 可加载指定的属性配置文件到环境变量,使用参见【组件赋值】。而 @ImportSource 则可以导入 Spring 配置文件,让配置文件中内容生效。因为在 SpringBoot 中默认没有 Spring 配置文件,我们自己编写的配置文件也不能自动识别,我们如果想要使用 Spring 配置文件,此时就可以使用该注解。

1、编写示例 Spring 配置文件:

<!-- beans.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 class="com.springboot.helloworld.pojo.Dog">
        <property name="name" value="bob"/>
        <property name="color" value="yellow"/>
    </bean>
</beans>

2、使用注解加载 Spring 配置文件:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;

@SpringBootApplication
@ImportResource("classpath:beans.xml")
public class HelloworldApplication {
    public static void main(String[] args) {
        SpringApplication.run(HelloworldApplication.class, args);
    }
}

3、测试:

import com.springboot.helloworld.pojo.Dog;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * SpringBoot 单元测试
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloworldApplicationTests {

    @Autowired
    private Dog dog;

    @Test
    public void test() {
        System.out.println(dog);
        /*
        Dog{name='bob', color='yellow'}
         */
    }
}
0

评论区