【问题标题】:@Value can not autowired from properities@Value 不能从属性自动装配
【发布时间】:2014-09-20 10:35:25
【问题描述】:

bean定义如下:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.client.RestTemplate;

import com.ma2oo.model.domain.User;
import com.ma2oo.model.res.interfaces.IUserService;

@Configuration
@PropertySource("classpath:exam-binary.properties")
public class UserServiceImpl implements IUserService {
    private static final RestTemplate restTemplate = new RestTemplate();

    @Value("${user.post.uri}")
    private String registerUri;

    public User register(final User user) {
        System.out.println(registerUri.toString());
        return restTemplate.postForObject(registerUri, user, User.class);
    }

    @Bean(name = "userServiceImpl")
    public IUserService getUserService() {
        return new UserServiceImpl();
    }
}

导入的属性文件位于src/main/resources 下。 变量是这样的:

user.post.uri=http://localhost:9000/users/newUser

调用这个函数的方法如下:

ApplicationContext applicationContext = new AnnotationConfigApplicationContext(UserServiceImpl.class);
IUserService userService = (UserServiceImpl) applicationContext.getBean("userServiceImpl");
User result = userService.register(register);

函数register() 的标准输出是${user.post.uri},这意味着该值不会自动装配。 异常描述为:

java.lang.IllegalArgumentException: Not enough variable values available to expand 'user.post.uri'

有人可以帮忙吗? 提前致谢。

【问题讨论】:

    标签: java spring mongodb rest properties


    【解决方案1】:

    尝试在您的配置中添加 bepropertySourcesPlaceholderConfigurer

       @Bean
       public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
          return new PropertySourcesPlaceholderConfigurer();
       }
    

    @PropertySource 注解不会自动向 Spring 注册 PropertySourcesPlaceholderConfigurer。相反,必须在配置中显式定义 bean 才能使属性解析机制正常工作。[reference]

    spring docs.了解更多信息

    【讨论】:

      猜你喜欢
      • 2015-10-02
      • 2015-04-17
      • 2011-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-08
      • 2015-09-17
      • 1970-01-01
      相关资源
      最近更新 更多