我正在尝试读取Util
类中的属性值。我试过Environment
了@Value
。但它Null
为这些领域带来了价值。
@SpringBootApplication
@EnableJpaAuditing
public class EmployeeApplication {
@PostConstruct
private void init() {
System.out.println("AppInitializator initialization logic ...");
new Util().getTime();
}
public static void main(String[] args) throws Exception {
SpringApplication.run(EmployeeApplication.class, args);
}
}
public class Util {
@Autowired
private Environment env;
@Value("${defaultTimeFormat}")
private String defaultTimeFormat;
public void getTime(){
System.out.println(defaultTimeFormat);
System.out.println(env.getProperty("defaultTimeFormat"));
// method logic here
}
}
我通过将 Util 作为@Service
类并将其依赖项注入EmployeeApplication
如下来解决了这个问题。
@SpringBootApplication
@EnableJpaAuditing
public class EmployeeApplication {
@Autowired
Util util;
@PostConstruct
private void init() {
System.out.println("AppInitializator initialization logic ...");
util.getTime();
}
public static void main(String[] args) throws Exception {
SpringApplication.run(EmployeeApplication.class, args);
}
}
@Service
public class Util {
@Autowired
private Environment env;
@Value("${defaultTimeFormat}")
private String defaultTimeFormat;
public void getTime(){
System.out.println(defaultTimeFormat);
System.out.println(env.getProperty("defaultTimeFormat"));
// method logic here
}
}
但是正确的方法是spring-boot
什么?我需要让它Service/Component/Repository
从属性文件中读取吗?