注释@Value在我的服务中不起作用

时间:2019-06-04 05:18:52

标签: spring spring-mvc

我有我的主要配置

    @EnableScheduling
    @Configuration
    @EnableWebMvc
    @ComponentScan(basePackages = { "gr.citystore.web.helios.yeastar" })
    @PropertySource(value = { "classpath:application.properties" })
    public class HelloWorldConfiguration extends WebMvcConfigurerAdapter {

        @Autowired
        private MyServiceImpl myService;

        @EventListener(ContextRefreshedEvent.class)
        public void contextRefreshedEvent() {
            MyThread mThread = new MyThread(myService);
        }
}

我的服务代码是:

@Service("myService")
@PropertySource(value = { "classpath:application.properties" })
public class MyServiceImpl implements MyService{

    @Value("${property.api.ip}")
    private String apiIP;
    @Value("${property.api.port}")
    private String apiPort;

    public String myMethod() {

    }

} 

我的问题是@Value注释在我作为myThread中的参数传递时不起作用,而是返回“ $ {property.api.port}”。 我在这里想念什么?

编辑: application.properties文件的位置为“ src / main / resources”,内容为:

property.api.ip = 12.34.50.30
property.api.port = 50034

1 个答案:

答案 0 :(得分:0)

您可以像这样将application.properties的值注入您的类中:

@Service("myService")
public class MyServiceImpl implements MyService{

    private final String apiIP;

    private final String apiPort;

    public MyServiceImpl(@Value("${property.api.ip}") String apiIP,
              @Value("${property.api.port}") apiPort) {
         this.apiIP = apiIP;
         this.apiPort = apiPort;
    }

    public String myMethod() {

    }

}