1.加在@Bean
package com.knife.EhcacheBoot;
public class ServiceA {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString(){
return "[id:"+id+",name:"+name+"]";
}
}
package com.knife.EhcacheBoot;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class Config {
@Bean
@ConfigurationProperties(prefix = "service")
public ServiceA createServiceA() {
return new ServiceA();
}
}
配置文件
service.id=001
service.name=test
测试
package com.knife.EhcacheBoot;
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.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = App.class)//这里的App是springboot的启动类名
@WebAppConfiguration
public class UnitTest {
@Autowired
ServiceA sa;
@Test
public void test(){
System.out.println(sa);
}
}
结果
[id:001,name:test]
2.加在class上
package com.knife.EhcacheBoot;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "service")
public class ServiceA {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString(){
return "[id:"+id+",name:"+name+"]";
}
}
package com.knife.EhcacheBoot;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class Config {
@Bean
public ServiceA createServiceA() {
return new ServiceA();
}
}