【问题标题】:why properties file can not be imported为什么无法导入属性文件
【发布时间】:2014-08-25 17:17:57
【问题描述】:

属性文件是src\main\resources\exam-binary.properties。 Exam-binary.properties 中的内容是:

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

导入类如下,但是,似乎无法导入该值。

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

import com.ma2oo.model.domain.User;

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

    @Value("${user.post.url}")
    private String registerUrl;

    public User Register(final User user) {
        System.out.println("url print: " + registerUrl);
        return restTemplate.postForObject(registerUrl, user, User.class);
    }
}

我有@EnableAutoConfiguration,它将涵盖所有课程。调用 RegisterUser 的方法是:

@RequestMapping(value = {"/signUp"}, method = RequestMethod.POST)
public ModelAndView signUp(@ModelAttribute("user") User user) {
    new RegisterUser().Register(user);
    return new ModelAndView("quiz_start");
}

标准输出为:

url print: null

谁能帮助解释为什么@PropertySource 不起作用? 提前致谢。

【问题讨论】:

  • 你是如何使用这个RegisterUser类的?
  • 使用new RegisterUser().Register(user),我还有另一个注释@EnableAutoConfiguration 将涵盖所有这些类,不太确定它是否正确。
  • 请将其添加到您的问题中。
  • 基本上,您是在自己创建实例。 Spring 绝对不涉及。向我们展示您正在尝试做什么,以便我们更好地帮助您。
  • 我认为@EnableAutoConfiguration 会启用弹簧。对吗?

标签: java spring spring-mvc properties


【解决方案1】:

根本原因是您使用的RegisterUser 实例不是Spring 托管bean。相反,您自己创建了它

new RegisterUser() // spring has no knowledge of it

为什么这个类是Configuration 类?您似乎将其用作服务。将属性配置移动到正确的 @Configuration 类,声明 RegisterUser 类型的 bean 并在 @RequestMapping 注释方法中使用该 bean。

【讨论】:

  • 谢谢大佬,我按照你说的改了,效果很好。非常感谢。
猜你喜欢
  • 2012-04-19
  • 2022-08-12
  • 2021-10-24
  • 2017-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多