第一種 @PropertySource
Annotation providing a convenient and declarative mechanism for adding a PropertySource to Spring's Environment. To be used in conjunction with
@Configuration
classes.
@Configuration
@PropertySource("classpath:/com/myco/app.properties")
public class AppConfig {
@Autowired
Environment env;
@Bean
public TestBean testBean() {
TestBean testBean = new TestBean();
testBean.setName(env.getProperty("testbean.name"));
return testBean;
}
}
- 可以自定properties文檔已經(jīng)路徑
- 常用文件類型properties给涕、yml
- 配合
@configuration
使用 - 傾向于配置參數(shù)
第二種 @ImportResource
Indicates one or more resources containing bean definitions to import.
Like@Import
, this annotation provides functionality similar to the <import/> element in Spring XML. It is typically used when designing @Configuration classes to be bootstrapped by an AnnotationConfigApplicationContext, but where some XML functionality such as namespaces is still necessary.
@ImportResource("classpath:config.xml")
public class Config{
}
- 常用文件類型xml
- 傾向于功能初始化衙四。例如:早期springboot集成dubbo啟動(dòng)時(shí)(現(xiàn)在dubbo可以注解集成了)
@SpringBootApplication
@ImportResource("dubbo-services.xml")
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
第三種 @Value(本質(zhì)其實(shí)也是第一種)
Annotation at the field or method/constructor parameter level that indicates a default value expression for the affected argument. Typically used for expression-driven dependency injection. Also supported for dynamic resolution of handler method parameters, e.g. in Spring MVC. A common use case is to assign default field values using "#{systemProperties.myProp}" style expressions.
@Value("{server.port}")
String port;
- 默認(rèn)是系統(tǒng)application.properties/yml文件
文件的定義方式-數(shù)組
errorcodes[0]=1234
errorcodes[1]=1234
errorcodes[2]=1234
errorcodes[3]=1234
文件的定義方式-MAP
errorcode_map[1000]=error1
errorcode_map[3001]=error2
errorcode_map[3002]=error3