第一种 @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文档已经路径
- 常用文件类型properties、yml
- 配合
@configuration
使用 - 倾向于配置参数
第二种 @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启动时(现在dubbo可以注解集成了)
@SpringBootApplication
@ImportResource("dubbo-services.xml")
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
第三种 @Value(本质其实也是第一种)
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;
- 默认是系统application.properties/yml文件
文件的定义方式-数组
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
网友评论