spring - 从类的静态字段中的属性文件中读取属性值

     2023-02-26     57

关键词:

【中文标题】spring - 从类的静态字段中的属性文件中读取属性值【英文标题】:spring - read property value from properties file in static field of class 【发布时间】:2014-08-30 04:57:04 【问题描述】:

我有一个实用程序类,其中我有一种方法需要用户名和密码才能连接其他 url。我需要将该用户名保存在属性文件中,以便我可以随时更改它。但是当我在静态方法(作为实用程序类)中使用它时,问题是它显示为空。(即它无法从属性文件中读取)。

但是当我在其他一些控制器中检查这些值时,它们就会到达那里。 所以我的问题是如何读取静态字段中的属性值

<bean
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>classpath*:/myservice_detaults.properties</value>
            <value>classpath*:/log4j.properties</value>
        </list>
    </property>
</bean>

//在Utitlity类代码中

  @Value("$app.username")
      static String userName;

public static connectToUrl()
  //use userName
 //userName showing null

【问题讨论】:

你的实用程序类是如何加载/注入的? 我的实用程序类是普通类而不是弹簧类,并且像普通静态调用一样调用 connectToUrl 如果你的实用程序类没有被spring上下文加载,你不能在其中注入参数。但是,您仍然可以使用@AmitChotaliya 提出的解决方案。 Spring 的一个好的做法是使用由 spring 上下文加载的单例 bean,而不是实用程序类中的静态方法。 @superbob 谢谢,我猜 AmitChotaliya 提供的解决方案应该可以解决我的问题。我会试试。但是你能解释一下你的观点吗>>“Spring的一个好习惯是使用由spring上下文加载的单例bean而不是实用程序类中的静态方法。”..任何链接了解更多信息 这有很多原因,但至少,您可以正确初始化 @Value("$app.username") 属性,而无需做任何特别的事情。如果你想要一些链接,这个问题的第二个答案可以给你更多的“论据”***.com/questions/7270681/…。根据我自己的经验,仅当我不需要初始化来使用它们(这不是你的情况)时,我才在实用程序类上使用静态方法。否则,我使用弹簧豆。 【参考方案1】:

Spring 不允许将值注入非最终静态字段,但将您的字段设为私有并且它应该可以工作。

【讨论】:

您想指出提供此信息的任何参考【参考方案2】:

Utility 类中,您可以使用setter 方法来设置属性,然后您可以使用MethdInvokingFactoryBean

class Utility
    static String username;
    static String password;
    public static setUserNameAndPassword(String username, String password)
        Utility.username = username;
        Utility.password = password;
    
    //other stuff


<bean
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>classpath*:/myservice_detaults.properties</value>
            <value>classpath*:/log4j.properties</value>
        </list>
    </property>
</bean>

<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="staticMethod" value="foo.bar.Utility.setUserNameAndPassword"/>
    <property name="arguments">
        <list>
            <value>$username</value>
            <value>$password</value>
        </list>
   </property>
</bean>

【讨论】:

【参考方案3】:
Read property value from properties file in static field of class using Java based spring configuration.
Example :
// The property file to store fields.
user.properties
     username=Elijah Wood
     age=26
     language=English
// This class holds the static values

包 org.javahive.propertyreader.example;

public class UserDetails 

    static String username;
    static String age;
    static String language;

    public static void setUserValues(String username, String age, String language) 
        UserDetails.username = username;
        UserDetails.age = age;
        UserDetails.language = language;
    


//Spring configuration class

package org.javahive.propertyreader.example;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.MethodInvokingFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

@Configuration
@ComponentScan(value =  "org.javahive.propertyreader.example" )
@PropertySource("classpath:user.properties")
public class PropertyReaderConfig 

    @Value("$user")
    private String username;

    @Value("$age")
    private String age;

    @Value("$language")
    private String language;

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigIn() 
        return new PropertySourcesPlaceholderConfigurer();
    

    @Bean
    public MethodInvokingFactoryBean methodInvokingFactoryBean() 
        MethodInvokingFactoryBean mifb = new MethodInvokingFactoryBean();
        mifb.setStaticMethod("org.javahive.propertyreader.example.UserDetails.setUserValues");
        mifb.setArguments(new String[]  this.username, this.age, this.language );
        return mifb;
    

    /**
     * @return the name
     */
    public String getName() 
        return username;
    

    /**
     * @param name
     *            the name to set
     */
    public void setName(String name) 
        this.username = name;
    

    /**
     * @return the age
     */
    public String getAge() 
        return age;
    

    /**
     * @param age
     *            the age to set
     */
    public void setAge(String age) 
        this.age = age;
    

    /**
     * @return the language
     */
    public String getLanguage() 
        return language;
    

    /**
     * @param language
     *            the language to set
     */
    public void setLanguage(String language) 
        this.language = language;
    



//The main class.

包 org.javahive.propertyreader.example;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main 

    public static void main(String[] args) 
        ApplicationContext context = new AnnotationConfigApplicationContext(PropertyReaderConfig.class);
        System.out.println("User Name : " + UserDetails.username);
        System.out.println("Age : " + UserDetails.age);
        System.out.println("Language : " + UserDetails.language);
    

【讨论】:

【参考方案4】:

或者只是

<bean id="constants" class="com.foo.constants.CommonConstants">
    <property name="username" value="$username"/>
</bean>

【讨论】:

【参考方案5】:

或者在username 的非静态setter 方法上使用@Value 例如。

@Value("$app.username")
public void setUserName(String userName) 
    UtilityClass.userName = userName;

【讨论】:

【参考方案6】:

试试这个: 让你的类成为一个组件

@Component
public class UserXXXUtils 
    private static Integer trustXXXMask;

    @Value("$trustXXXMask")
    public void setTrustXXXMask(Integer trustXXXMask) 
        UserXXXUtils.trustXXXMask = trustXXXMask;
    
    //Access anywhere in the class

【讨论】:

java示例代码_读取spring项目中的属性文件

java示例代码_读取spring项目中的属性文件 查看详情

从类库项目中的 App.config 中读取

】从类库项目中的App.config中读取【英文标题】:ReadfromApp.configinaClassLibraryproject【发布时间】:2012-04-0922:42:23【问题描述】:我正在开发一个简单的类库项目,它会给我一个dll。我想从配置文件中读取一个特定的值。所以我在我... 查看详情

无法从 Spring Boot 中的外部属性文件中读取值

】无法从SpringBoot中的外部属性文件中读取值【英文标题】:UnabletoreadvaluesfromexternalpropertyfileinSpringBoot【发布时间】:2018-06-2400:59:35【问题描述】:我有一个正在运行的SpringBoot项目。我想从外部属性文件中读取一些特定于环境的... 查看详情

在 Python(tkinter)中从类的外部更改类的私有属性(标签)

】在Python(tkinter)中从类的外部更改类的私有属性(标签)【英文标题】:Changingprivateattributes(labels)ofaClassfromoutsideofitinPython(tkinter)【发布时间】:2021-08-1307:26:29【问题描述】:我在Python中使用tkinter制作了一个GUI,我创建了一个... 查看详情

Spring ConditionalOnProperty 无法读取 custom.properties 文件中的属性

】SpringConditionalOnProperty无法读取custom.properties文件中的属性【英文标题】:SpringConditionalOnPropertycannotreadpropertyincustom.propertiesfile【发布时间】:2020-07-2203:47:38【问题描述】:您好,我有一些自定义属性文件,例如application.properties... 查看详情

无法从 Java Spring Boot 项目中的 application.yml 文件中读取用户定义类的列表

】无法从JavaSpringBoot项目中的application.yml文件中读取用户定义类的列表【英文标题】:Unabletoreadlistofuserdefinedclassfromapplication.ymlfileinaJavaSpringBootproject【发布时间】:2021-02-1302:45:43【问题描述】:团队您好,我最近尝试从SpringBoot项... 查看详情

jQuery - 从类的元素中获取属性值的列表

】jQuery-从类的元素中获取属性值的列表【英文标题】:jQuery-getalistofvaluesofanattributefromelementsofaclass【发布时间】:2011-02-1418:58:35【问题描述】:我有一个类.object,它有一个名为level的属性。我想在页面上获取level的所有不同值的... 查看详情

如何从类路径加载属性文件? [关闭]

】如何从类路径加载属性文件?[关闭]【英文标题】:Howtoloadpropertyfilefromclasspath?[closed]【发布时间】:2012-08-1500:23:55【问题描述】:getResourceAsStream()是java.lang.Class类的方法。此方法在类路径中找到具有给定名称的资源。实际上这... 查看详情

spring boot中的属性文件读取错误

】springboot中的属性文件读取错误【英文标题】:Propertyfilereadingerrorinspringboot【发布时间】:2021-11-2208:48:31【问题描述】:下面是我在SpringBoot应用中的yml文件stack:apiContext:data-servicedomainOwner:tratadomainContext:Madata-service#cluster:#servicePor... 查看详情

读取外部类的隐藏私有字段

...#a和#x。但实际上我只能读取#a,万一访问#x会报错:无法从类未声明的对象中读取私有成员#x似乎#x的类B阴影A的类似字段。首先,这似乎不合逻辑-为什么它以这种方式工作,如果它是故意的,那么它是以这种方式计划的吗?是否 查看详情

java静态资源(静态方法,静态属性)是程序一运行就加载到jvm中,还是当被调用的时候才进行加载呢?

...的。1、类中的静态属性会被加入到类对象(也可以叫做类的模板,是类的描述)的构造器中,静态方法也会被加入到类对象中。 2、当第一次使用类时,JVM会通过类加载器,加载类对象,从而初始化静态属性,并装入类的方... 查看详情

如何使用牛顿软从类的复杂类型属性中仅序列化特定值

】如何使用牛顿软从类的复杂类型属性中仅序列化特定值【英文标题】:howtoserializeonlyspecificvaluefromcomplextypepropertyofclassusingnewtonsoft【发布时间】:2021-08-1523:38:56【问题描述】:我有一个具有多个属性的类,其中一些属性是一种... 查看详情

注解形式读取properties文件中的属性

1、spring.xml中加入(多个properties用逗号隔开) <context:property-placeholderlocation="classpath:jdbc.properties,classpath:config.properties"/>2、spring-mvc.xml中加入(只加上面一句controller中读取不到值)<context:prop 查看详情

spring为类的静态属性实现注入

我们知道,正常情况下,spring的一个bean要依赖其他资源,如properties或其他bean,直接利用@Value或@Autowired就可以了。这两个注解就相当于springapplicationcontextxml文件定义bean时的property节点。相当于调用了每个属性的set方法。<beanid=... 查看详情

读取配置文件中的值

/***加载配置文件*@author**/publicclassConfigUtil{ //实例属性(对象属性) privatestaticPropertiesps=newProperties(); static{ /* *在加载类的同时,告诉类加载器,将此文件加载到内存 */ InputStreamin=ConfigUtil.class.getClassLoader().getReso 查看详情

java中的类

一:类的生命周期  类的生命周期从类被加载,连接和初始化开始!    到类的卸载结束!    01.类的生命周期中,类的2进制数据位于方法区;    02.在堆中会有一个描述这个类的Class对象;2.1加载... 查看详情

c#图解教程第六章深入理解类

深入理解类类成员成员修饰符的顺序实例类成员静态字段从类的外部访问静态成员静态字段示例静态成员的生存期静态函数成员其他静态类成员类型成员常量常量与静态量属性属性声明和访问器属性示例使用属性属性和关联字段... 查看详情

java静态资源(静态方法,静态属性)是程序一运行就加载到jvm中,还是当被调用的时候才进行加载呢

...)。1、类中的静态属性会被加入到类对象(也可以叫做类的模板,是类的描述)的构造器中,静态方法也会被加入到类对象中。 2、当第一次使用类时,JVM会通过类加载器,加载类对象,从而初始化静态属性,并装入类的方... 查看详情