Spring - using static final fields (constants) for bean initialization

前端 未结 5 871
轻奢々
轻奢々 2020-12-07 17:07

is it possible to define a bean with the use of static final fields of CoreProtocolPNames class like this:




        
相关标签:
5条回答
  • 2020-12-07 17:43

    One more example to add for the instance above. This is how you can use a static constant in a bean using Spring.

    <bean id="foo1" class="Foo">
      <property name="someOrgValue">
        <util:constant static-field="org.example.Bar.myValue"/>
      </property>
    </bean>
    
    package org.example;
    
    public class Bar {
      public static String myValue = "SOME_CONSTANT";
    }
    
    package someorg.example;
    
    public class Foo {
        String someOrgValue; 
        foo(String value){
            this.someOrgValue = value;
        }
    }
    
    0 讨论(0)
  • 2020-12-07 17:44

    don't forget to specify the schema location..

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
         http://www.springframework.org/schema/util  http://www.springframework.org/schema/util/spring-util-3.1.xsd">
    
    
    </beans>
    
    0 讨论(0)
  • 2020-12-07 17:45
    <util:constant id="MANAGER"
            static-field="EmployeeDTO.MANAGER" />
    
    <util:constant id="DIRECTOR"
        static-field="EmployeeDTO.DIRECTOR" />
    
    <!-- Use the static final bean constants here -->
    <bean name="employeeTypeWrapper" class="ClassName">
        <property name="manager" ref="MANAGER" />
        <property name="director" ref="DIRECTOR" />
    </bean>
    
    0 讨论(0)
  • 2020-12-07 17:56

    Something like this (Spring 2.5)

    <bean id="foo" class="Bar">
        <property name="myValue">
            <util:constant static-field="java.lang.Integer.MAX_VALUE"/>
        </property>
    </bean>
    

    Where util namespace is from xmlns:util="http://www.springframework.org/schema/util"

    But for Spring 3, it would be cleaner to use the @Value annotation and the expression language. Which looks like this:

    public class Bar {
        @Value("T(java.lang.Integer).MAX_VALUE")
        private Integer myValue;
    }
    
    0 讨论(0)
  • 2020-12-07 18:02

    Or, as an alternative, using Spring EL directly in XML:

    <bean id="foo1" class="Foo" p:someOrgValue="#{T(org.example.Bar).myValue}"/>
    

    This has the additional advantage of working with namespace configuration:

    <tx:annotation-driven order="#{T(org.example.Bar).myValue}"/>
    
    0 讨论(0)
提交回复
热议问题