2014-09-20 39 views
0

的bean定義是如下自動裝配:@Value不能從電學性能的研究

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' 

任何人都可以幫忙嗎? 在此先感謝。

回答

1

嘗試添加已經在你的配置propertySourcesPlaceholderConfigurer

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

@PropertySource註釋不會自動使用Spring註冊PropertySourcesPlaceholderConfigurer。相反,必須在配置中顯式定義bean以獲取屬性解析機制。 [reference]

spring docs.中閱讀更多關於