您的位置:首页 > 其它

加载自定义的配置文件

2018-01-26 00:00 288 查看

加载自定义的properties文件<br>

remote.properties

remote.uploadFilesUrl=/resource/files/
remote.uploadPicUrl=/resource/pic/


方式一

@ConfigurationProperties(prefix = "remote", ignoreUnknownFields = false)
@PropertySource("classpath:remote.properties")
@Component
public class RemoteProperties {
private String uploadFilesUrl;
private String uploadPicUrl;
}

@RestController
public class TestService{
@Autowired
RemoteProperties remoteProperties;

public void test(){
String str = remoteProperties.getUploadFilesUrl();
System.out.println(str);
}
}


方式二

@ConfigurationProperties(prefix = "remote", ignoreUnknownFields = false)
@PropertySource("classpath:remote.properties")
@Configuration
public class RemoteProperties {
private String uploadFilesUrl;
private String uploadPicUrl;
}

@RestController
public class TestService{
@Autowired
RemoteProperties remoteProperties;

public void test(){
String str = remoteProperties.getUploadFilesUrl();
System.out.println(str);
}
}


方式三

@ConfigurationProperties(prefix = "remote", ignoreUnknownFields = false)
@PropertySource("classpath:remote.properties")
public class RemoteProperties {
private String uploadFilesUrl;
private String uploadPicUrl;
}

@EnableConfigurationProperties(RemoteProperties.class)
@RestController public class TestService{ @Autowired RemoteProperties remoteProperties; public void test(){ String str = remoteProperties.getUploadFilesUrl(); System.out.println(str); } }


方式四

@PropertySource("classpath:remote.properties")
@Configuration
public class RemoteProperties {
@Value("${remote.uploadFilesUrl}")
private String uploadFilesUrl;
@Value("${remote.uploadPicUrl}")
private String uploadPicUrl;
@Bean
public  PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}

@RestController
public class TestService{
@Autowired
RemoteProperties remoteProperties;
public void test(){
String str = remoteProperties.getUploadFilesUrl();
System.out.println(str);
}
}

该方式一般只用于
SpringMVC
中<br>
@ConfigurationProperties(prefix = "remote", ignoreUnknownFields = false)
该注解用于绑定属性。prefix用来选择属性的前缀,也就是在remote.properties文件中的"remote",ignoreUnknownFields是用来告诉SpringBoot在有属性不能匹配到声明的域时抛出异常。<br>
@PropertySource("classpath:remote.properties")
配置文件路径<br>

加载自定义的xml文件

@Configuration
@ImportResource(locations={"classpath:application-bean.xml"})
publicclass ConfigClass {
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: