spring中@Value注解是非常方便的
说下在以java方式配时一点需要注意的地方
上代码看吧
1 package com.yangxin.springinaction.demo1; 2 3 import com.alibaba.druid.pool.DruidDataSource; 4 import org.springframework.beans.factory.annotation.Value; 5 import org.springframework.context.annotation.*; 6 import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; 7 import org.springframework.web.servlet.config.annotation.EnableWebMvc; 8 9 import javax.sql.DataSource; 10 11 12 /** 13 * Created by Administrator on 2017/2/27. 14 */ 15 @Configuration 16 @ComponentScan(excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,value = {EnableWebMvc.class})}) 17 @EnableAspectJAutoProxy 18 @PropertySource(value = "classpath:db.properties") 19 public class AppConfig { 20 21 // @Value("${jdbc.driver}") 22 // private String driver; 23 // 24 // @Value("${jdbc.url}") 25 // private String url; 26 // 27 // @Value("${jdbc.username}") 28 // private String username; 29 // 30 // @Value("${jdbc.password}") 31 // private String password; 32 33 //21 --- 31 行 这是取不到值得 作为方法入参可以取到 34 35 @Bean 36 public DataSource druidDataSource(@Value("${jdbc.driver}") String driver, 37 @Value("${jdbc.url}") String url, 38 @Value("${jdbc.username}") String username, 39 @Value("${jdbc.password}") String password) { 40 DruidDataSource druidDataSource = new DruidDataSource(); 41 42 druidDataSource.setDbType("mysql"); 43 44 druidDataSource.setDriverClassName(driver); 45 46 druidDataSource.setUrl(url); 47 48 druidDataSource.setUsername(username); 49 druidDataSource.setPassword(password); 50 51 druidDataSource.setMaxActive(10); 52 druidDataSource.setMinIdle(5); 53 54 try { 55 druidDataSource.setFilters("stat, wall"); 56 } catch (Exception e) { 57 e.printStackTrace(); 58 } 59 60 return druidDataSource; 61 } 62 63 //这个bean不要忘记配置 如果不配置 上面取得的值为 @Value中的表达式 显然是不符合情况的 64 @Bean 65 public PropertySourcesPlaceholderConfigurer propertyConfigInDev() { 66 return new PropertySourcesPlaceholderConfigurer(); 67 } 68 69 }
时间: 2024-10-17 11:11:53