Spring读取配置项
Spring读取Properties文件
resources/app.properties文件
name=hello
age=23
Environment读取配置文件
指定数据源,注入Environment对象。
@Configuration @PropertySource("classpath:app.properties") public class EnvironmentStyleConfig{ @Autowired private Environment env; @PostConstruct public void println(){ System.out.println("name=" + env.getProperty("name")); System.out.println("age=" + env.getProperty("age")); } }
用到的方法主要有:
- env.getProperty("name");获取String类型
- env.getRequiredProperty("name");获取String类型而且不能为空,为空则报错
- env.getProperty("fistname", "无名");获取String类型,如果为空则附一个默认值
- env.getProperty("age", Integer.class);获取指定类型的值
- env.getProperty("myage", Integer.class, 0);获取指定类型的值,如果为空则设置一个默认值
使用占位符
指定数据源,使用@Value(“${name}”)
@Configuration @PropertySource("classpath:app.properties") public class PlaceholderStyleConfig { @Value("${name}") private String name; @Value("${age}") private Integer age; /** * Spring 4.0.7.RELEASE的话还需要配置PropertySourcesPlaceholderConfigurer * * @return */ @Bean public PropertySourcesPlaceholderConfigurer placeholder() { return new PropertySourcesPlaceholderConfigurer(); } @PostConstruct public void println() { System.out.println("name=" + name); System.out.println("age=" + age); } }
使用SpEL
@Configuration @PropertySource("classpath:app.properties") public class SpELStyleConfig { @Value("#{environment['name']}") public String name; @PostConstruct public void println() { System.out.println("name=" + name); } }
使用原生的Properties加载配置项
@Configuration public class PropertiesStyleConfig { private Properties properties; public Properties getProperties() { return properties; } @PostConstruct public void loadConfig() { InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("app.properties"); properties = new Properties(); try { properties.load(inputStream); } catch (IOException e1) { e1.printStackTrace(); } System.out.println("name:" + properties.getProperty("name") + ",age:" + properties.getProperty("age")); } }

浙公网安备 33010602011771号