application.properties:
authname=shphyl net.ebh=svnlan
默认的配置文件中可以直接获取
/** * 第一种方式 value("${name}") */ @Value("${authname}") private String authname; @RequestMapping("getname") public String getAuthname() { return "my name is " + authname; }
/** * 第二种方式直接注入Environment,通过environment.getProperty("name")来获取属性 */ @Autowired Environment environment; @RequestMapping("get") public String getname() { return environment.getProperty("net.ebh"); }
/** * 第三种直接获取配置文件 */ public String getProperties(String key) { try { Properties properties = PropertiesLoaderUtils.loadProperties(new ClassPathResource("application.properties")); return properties.getProperty(key); } catch (IOException e) { e.printStackTrace(); } return null; } @RequestMapping("getfile") public String getFile() { String authname = getProperties("authname"); String ebh = getProperties("net.ebh"); return authname + "--" + ebh; }
如果用户需要自定义配置文件,则需要配置来获取
my.properties
users.name=shphyl users.age=12 users.sex=male
通过get set方法来获取
@Configuration @ConfigurationProperties(prefix = "users") @PropertySource("classpath:config/my.properties") public class User { private String name; private int age; private String sex; //get set 省略 }
直接注入User通过get set即可获取各个属性
@Autowired User user; @RequestMapping("getproperties") private String getMyproperties() { return user.getName() + "--" + user.getSex() + "--" + user.getAge(); }