spring boot外部化配置标签详解

@Component

@Component:证明此组件是容器中的组件

@value

@value
对配置文件的数据进行单个绑定

@ConfigurationProperties

@ConfigurationProperties
对配置文件的数据进行批量绑定

@PropertySource

@PropertySource
可以指定外部配置文件

@ImportResource

@ImportResource
读取外部配置文件如xml文件
示例:
在main的java包下随意建一个java类代码如下

package com.boot2.bean;

public class Imbean {

}
后在resources下建一个xml文件代码如下:
bean的class绑定为你之前在java下新建的类,id名随意

<?xml version="1.0" encoding="UTF-8"?>




然后在项目生成的测试类中加入如下代码,测试是否成功调用xml文件中的bean,括号中的值为你在xmlbean中指定的id

package com.boot2;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;

@SpringBootTest
class Boot2ApplicationTests {
@Autowired
ApplicationContext app;

@Test
void contextLoads() {
    System.out.println(app.containsBean("imbean"));
}

}

别急着运行,最后在运行类中加入@ImportResource(locations = “classpath:imbean.xml”)括号中为你自己新建的xml文件

package com.boot2;

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

@SpringBootApplication
@ImportResource(locations = “classpath:imbean.xml”)
public class Boot2Application {
public static void main(String[] args) {
SpringApplication.run(Boot2Application.class, args);
}
}

@Configuration

@Configuration
指明当前类是一个配置类,替代@ImportResource指定的spring配置文件(xml)
首先在main的java包下随意建一个java类代码如下:
调用的类为之前创建的类,有问题的话可以去上面再次查看

package com.boot2.bean;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class inbeans {
@Bean
public Imbean testimbean(){
return new Imbean();
}
}

之后就只用在测试类里调用即可

package com.boot2;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;

@SpringBootTest
class Boot2ApplicationTests {
@Autowired
ApplicationContext app;

@Test
void contextLoads() {
    System.out.println(app.containsBean("inbeans"));
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值