加载自定义的properties文件<br>
remote.properties
remote.uploadFilesUrl=/resource/files/ remote.uploadPicUrl=/resource/pic/
-
方式一
@ConfigurationProperties(prefix = "remote", ignoreUnknownFields = false)@PropertySource("classpath:remote.properties")@Componentpublic class RemoteProperties {private String uploadFilesUrl;private String uploadPicUrl;}
@RestControllerpublic 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")@Configurationpublic class RemoteProperties {private String uploadFilesUrl;private String uploadPicUrl;}
@RestControllerpublic 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)@RestControllerpublic class TestService{ @Autowired RemoteProperties remoteProperties; public void test(){ String str = remoteProperties.getUploadFilesUrl(); System.out.println(str); }}
-
方式四
@PropertySource("classpath:remote.properties")@Configurationpublic class RemoteProperties { @Value("${remote.uploadFilesUrl}") private String uploadFilesUrl; @Value("${remote.uploadPicUrl}") private String uploadPicUrl; @Bean public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); }}
@RestControllerpublic 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 {}