@Value注释失效
一、@Value的注意事项
1.不能作用于静态变量(static);
2.不能作用于常量(final);
3.不能在非注册的类中使用(类需要被注册在spring上下文中,如用@Service,@RestController,@Component等);
4.使用这个类时,只能通过依赖注入的方式,用new的方式是不会自动注入这些配置的。
/** * 抽象工厂+反射 */ //不能在非注册的类中使用(类需要被注册在spring上下文中,如用@Service,@RestController,@Component等); public class SimpleAbstractFactory { @Value("${packName}") //不能作用于静态变量(static) private static String packName; @Value("${sqlName}") //不能作用于常量(final); private final String sqlName; public IUser CreateUser() throws Exception{ String className=packName+"."+sqlName+"IUser"; return (IUser)Class.forName(className).newInstance(); } public IDepartment CreateDepartment() throws Exception{ String className=packName+"."+sqlName+"IDepartment"; return (IDepartment)Class.forName(className).newInstance(); } } @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:spring-config.xml"}) public class MainToken{ @Test public void testToken() { try{ //使用这个类时,只能通过依赖注入的方式,用new的方式是不会自动注入这些配置的。 SimpleAbstractFactory simpleAbstractFactory=new SimpleAbstractFactory(); User user=new User(); Department department=new Department(); IDepartment idp=simpleAbstractFactory.CreateDepartment(); IUser ius=simpleAbstractFactory.CreateUser(); idp.insert(department); idp.getDepartment(Long.valueOf(1)); ius.insert(user); ius.getUser(Long.valueOf(1)); }catch(Exception e){ } } } 三、正确的方式 /** * 抽象工厂+反射 */ @Service public class SimpleAbstractFactory { @Value("${packName}") private String packName; @Value("${sqlName}") private String sqlName; public IUser CreateUser() throws Exception{ String className=packName+"."+sqlName+"IUser"; return (IUser)Class.forName(className).newInstance(); } public IDepartment CreateDepartment() throws Exception{ String className=packName+"."+sqlName+"IDepartment"; return (IDepartment)Class.forName(className).newInstance(); } } @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:spring-config.xml"}) public class MainToken { @Autowired //使用这个类时,只能通过依赖注入的方式,用new的方式是不会自动注入这些配置的。 private SimpleAbstractFactory simpleAbstractFactory; @Test public void testToken() { try{ User user=new User(); Department department=new Department(); IDepartment idp=simpleAbstractFactory.CreateDepartment(); IUser ius=simpleAbstractFactory.CreateUser(); idp.insert(department); idp.getDepartment(Long.valueOf(1)); ius.insert(user); ius.getUser(Long.valueOf(1)); }catch(Exception e){ } } }
春有百花秋有月,夏有凉风冬有雪!