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'
有人可以帮忙吗? 提前谢谢。
答案 0 :(得分:1)
尝试在配置中添加propertySourcesPlaceholderConfigurer
,
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
@PropertySource注释不会自动向Spring注册PropertySourcesPlaceholderConfigurer。相反,必须在配置中显式定义bean才能使属性解析机制正常工作。[reference]
中详细了解相关信息