问题描述
- 为什么我用spring注解读不到我配置文件里面的值??
-
//运用注解读取配置文件
@Component
@ComponentScan
@Configuration
@PropertySource({ "classpath:/info.properties" })
public class PropertiesResolve {
private static Logger logger = Logger.getLogger(PropertiesResolve.class.getName());//把配置文件的属性值直接注解到类的属性里面 @Value("${mongodb.url}") //url static String mongodbUrl; @Value("${mongodb.name}") //name static String mongodbName; @Value("${mongodb.password}") //password static String mongodbPassword; @Bean public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() { return new PropertySourcesPlaceholderConfigurer(); } @Scheduled(cron = "${time1}") public static void test1(){ logger.info("1111111111111111111111111"); System.out.println("mongodbUrl的值: "+mongodbUrl); System.out.println("mongodbName的值: "+mongodbName); System.out.println("mongodbPassword的值: "+mongodbPassword); }
//*************************************************************************************
@Autowired private static Environment env; @Scheduled(cron = "${time2}") public static void test2(){ logger.info("2222222222222222222222"); System.out.println(env.getProperty("mongodb.url")); System.out.println(env.getProperty("mongodb.name")); System.out.println(env.getProperty("mongodb.password")); }
}
配置文件内容:
##mongodbUrl##
mongodb.url = 127.0.0.1
##mongodbName##
mongodb.name= xs@tt.cok
##mongodbPassword##
mongodb.password= 1245sdsh
##time##
time1 = 0/20 * * * * ?
time2 = 0/58 * * * * ?test1输出:
mongodbUrl的值: null
mongodbName的值: null
mongodbPassword的值: nulltest2方法直接报错,错误为:java.lang.NullPointerException,
就算是static String mongodbUrl属性去掉static也是一样的错误,求大神帮忙
解决方案
解决方案二:
你的配置文件指定错误,classpath后面直接跟文件名称,要去掉/,修正如下试试:
@PropertySource({ "classpath:info.properties" })
时间: 2024-11-02 06:01:34