config.name=confignameconfig.password=configpassword
@Configuration@ConfigurationProperties(prefix = "config")@PropertySource("classpath:/config.properties")public class Config { private String name; private String password; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; }}
@EnableConfigurationProperties({Config.class})
使用的时候直接注入即可@AutowiredConfig config;
@ComponentScans({@ComponentScan("com.dx.controller"), @ComponentScan("app.config")})
@Configuration/** * 进行包扫描 * @author Administrator * *//* @ComponentScan(basePackages = "com.dxz.demo.configuration") *//** * 导入其他spring配置文件 * @author Administrator * *//* @ImportResource("classpath:applicationContext-configuration.xml") *//** * 导入其他@Configuration * @author Administrator * *//* @Import(UserConfig.class) */public class SpringConfig { public SpringConfig() { System.out.println("初始化spring配置文件SpringConfig"); } @Bean(name = "role") public Role role() { return new Role(); } /** * 嵌套@Configuration 必须时静态类 * @author Administrator * */ /* * @Configuration static class DatabaseConfig { //@Bean } */ public static void main(String[] args) { //获取SpringConfig配置文件,已注解的方式@Configuration ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); Role role = (Role) context.getBean("role"); } }
@Value("${test.u}") private String name = "用户名";