spring学习笔记
一、@Value注解
1.@Value Example
#{expression?:default value}
Few examples
@Value("#{systemProjecties['mongodb.port']?:27017}")private String mongodbPort;@Value("#{config['mongodb.url']?:'127.0.0.1'}")private String mongodbUrl;@Value("#{aBean.age ?:21}")private int age;
2.@Value And Property Example
${property:default value}
Few examples
//@propertySource("classpath:/config.properties")//configuration@Value("${mongodb.url:127.0.0.1}")private String mongodbUrl;@Value("#{'${mongodb.url:172.0.0.1}'}")private String mongoUrl;@Value("#config['mongodb.url']?:'127.0.0.1'")private String mogodbUrl;
config.propertymogodb.url = 1.2.3.4mogodb.db = hello
For "config" bean
<util:properties id="config" location="classpath:config.properties"/>
Follow up
Must register a static PropertySourcesPlaceholderConfiger bean in either XML or annotation ,so that Spring @Value konw how to interpret ${}
//@PropertySource("classpath:/config.properties}")//@Configuration@Beanpublic static PropertySourcesPlaceholderConfigurer propertyConfigIn() {return new PropertySourcesPlaceholderConfigurer();}
我的理解:
首先是#和
@Value注解应该是识别#的,#中可以写配置在xml中的“util”属性中的id的。
{}获取了。
如果没有设置PropertySourcesPlaceholderConfiger这个类,就不要用的方式吧。
另外要注意的是,如果你使用的是$,那么表达式的规则是default value前面是不需要写?的,否则的话,需要些?
二、ModelAttribute注解
ModelAttribute可以用在方法上和参数中
用在参数中的时候,用于解释model entity
我的理解是:在注解之后的Pet pet,无论参数写的是pet还是pet2,实际都对应的是model 中传过来的pet。
public String processSubmit(@ModelAttribute("pet") Pet pet, BindingResult result) {}
用在方法上的时候,表示该controller的所有方法在调用前,先执行此@ModelAttribute方法。并且如果注解中传过来的参数,可以返回到view中。
@ModelAttribute("accounts")public List<Account> getAccounts() {System.out.println("getAccounts");return accounts;}

浙公网安备 33010602011771号