简体   繁体   English

Spring:如何从Model类的属性文件中获取值

[英]Spring : how to get values from properties file in Model class

I am using Spring MVC for project. 我正在为项目使用Spring MVC。 I have some constant values which is stored in properties file and I want to fetch from properties file. 我有一些常量值存储在属性文件中,我想从属性文件中获取。 Question I am unable to fetch values in Model Classes from properties file. 问题我无法从属性文件中获取模型类中的值。 It is getting null . 它正在变为null

项目浏览器

I have set property file location in servlet-context.xml 我已经在servlet-context.xml中设置了属性文件的位置

 <context:property-placeholder location="classpath:myproperties.properties" />

Now by using @Value annotation I inject value from properties file. 现在,通过使用@Value批注,我从属性文件中注入值。

@Component
class ModelTest {

     @Value("${fname}")
     private String fname;

     // Default Constructor
     public ModelTest(){
          Sysout(fname);      // getting null here
     }

     @PostConstruct
     public void initMembers(){
          Sysout(fname)      // Prints fname value properly    
     }

     public void setFname(String fname){
          this.fname=fname;
     }

     public String getFname(){
          return fname;
     }

     @Override
     public String toString() {
          Sysout(fname);
          return "ModelTest [variableFirst=" + variableFirst + "]"; 
     }
}

Here is ServiceTest class. 这是ServiceTest类。

@Service
class ServiceTest(){

    @Value("${fname}")
    private String fname;

    public String printTest(){
         sysout(fname);           // Prints fname value
         return new ModelTest().toString() // Prints null
    }
}

Here is ControllerHome Class : 这是ControllerHome类:

@Controller
public class ControllerHome {

     @Value("${fname}")
     private String fname;

     @Autowired
     private ServiceTest service;

     @RequestMapping("/")
     public @ResponseBody String printData(){
          sysout(fname);           // Prints fname value
          return service.printTest();  // Print null
     }
}

In model class fname is getting null while In controller and service class value is coming properly. 在模型类中,当在控制器和服务类中的值正确到达时,fname变为null。

is anyone face such issue? 有人面对这样的问题吗?

This is how I do it : 这是我的方法:

@Component
@PropertySource("classpath:myproperties.properties") // <-Add this.
class ModelTest {

     @Autowired
     private Environment env; 

     public void test(){
        String name = env.getProperty("name"); //Assuming you have a 'name' key in your myproperties.property
     }
}

When you say model class, do you mean the value passed to a controller method indicated by @ModelAttribute ? 当您说模型类时,您是说将值传递给@ModelAttribute指示的控制器方法吗?

If so, that class is created by ordinary constructor invocation through reflection. 如果是这样,则该类由普通的构造函数调用通过反射创建。 It is not a spring bean, and thus @Value does nothing. 它不是spring bean,因此@Value不执行任何操作。

Addressing your edit, I think there is some fundamental misunderstanding about how Spring works. 在处理您的编辑时,我认为对于Spring的工作方式存在一些基本的误解。

@Service
class ServiceTest(){

    @Value("${fname}")
    private String fname;

    public String printTest(){
        sysout(fname);           // Prints fname value
        // Calling new here means Spring does nothing
        // ModelTest is not a Spring bean
        // `@Component`, `@PostConstruct` and `@Value` in ModelTest mean nothing.
        return new ModelTest().toString() // Prints null
    }
}

Instead, you have to do something like this: 相反,您必须执行以下操作:

@Service
class ServiceTest(){

    @Value("${fname}")
    private String fname;

    @Autowired
    private ModelTest modelTest;

    public String printTest(){
        sysout(fname);           // Prints fname value
        // modelTest is now a Spring bean
        return modelTest.toString() // Should not print null
    }
}

Now, Spring will create ModelTest , and @Component , @PostConstruct and @Value will be honored by Spring. 现在,春天将创建ModelTest@Component@PostConstruct@Value将被Spring荣幸。

However, @Component by itself has a default singleton scope. 但是, @Component本身具有默认的单例作用域。 So, you will have the same modelTest always. 因此,您将始终具有相同的modelTest

So, you have to do something like this: 因此,您必须执行以下操作:

@Component
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
class ModelTest {
    // ...
}

Now, while the modelTest reference in ServiceTest will remain constant, the use of a proxy will divert the method calls to a new instance of ModelTest , created by Spring, per request. 现在,尽管ServiceTestmodelTest引用将保持不变,但是使用代理将根据每个请求将方法调用转移到Spring创建的ModelTest的新实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM