Reputation: 11
I used java @Value like this, it works fine, and the variable "baiduurl" can be resolved correctly:
package com.lanyyyy.springdemo.controllers;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.lanyyyy.springdemo.service.*;
@RestController
public class GetURL {
@Value("${baiduurl}")
public String baiduurl;
@RequestMapping(path="/getbaidu", method=RequestMethod.GET)
public String getBaiduurl(){
// return "hello";
return baiduurl;
}
}
======================
But when I use like this, the variabe "baiduurl" can not be resolved:
package com.lanyyyy.springdemo.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
@PropertySource("classpath:application.properties")
public class UrlService {
@Value("${baiduurl}")
public String baiduurl;
// @RequestMapping(path="/getbaidu", method=RequestMethod.GET)
public String getBaiduurl() {
return baiduurl;
}
}
Is there anything wrong????? Or I use the @Value wrong?????
In my applicaiton.properties:
baiduurl=http://www.baidu.com
server.port=8888
Upvotes: 0
Views: 474
Reputation: 18235
When you annotated your controller as @RestController
then your class will become a @Controller
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController
A @Controller
annotated class is a @Component
:
@Documented
@Component
public @interface Controller
During component scan, spring container will initialize your class, @Autowire
fields and inject @Value
In your second example, your UrlService
is not a bean so no binding/injecting is done.
You should mark your service with @Service
(or other marker like @Component
...) to have the spring container injected baiduurl
value for you.
Upvotes: 5