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文件中的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"));
}
}