IT박스

스프링 인젝션 값을 정적 필드에 만드는 방법

itboxs 2020. 11. 11. 08:24
반응형

스프링 인젝션 값을 정적 필드에 만드는 방법


이전에 질문 한 것처럼 보일 수 있지만 여기서 다른 문제에 직면 해 있습니다.

정적 메서드 만있는 유틸리티 클래스가 있습니다. 나는 그렇지 않으며 그것에서 인스턴스를 가져 가지 않을 것입니다.

public class Utils{
    private static Properties dataBaseAttr;
    public static void methodA(){

    }

    public static void methodB(){

    }
}

이제 데이터베이스 속성 Properties.Spring 구성으로 dataBaseAttr을 채우려면 Spring이 필요합니다.

<?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.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">

<util:properties id="dataBaseAttr"
        location="file:#{classPathVariable.path}/dataBaseAttr.properties" />
</beans>

나는 이미 다른 빈에서 그것을 수행했지만 여기이 클래스 (Utils)의 문제는 빈이 아닙니다. 빈으로 만들면 클래스가 인스턴스화되지 않고 항상 변수이기 때문에 여전히 변수를 사용할 수 없습니다. null과 같습니다.


두 가지 가능성이 있습니다.

  1. 정적 속성 / 필드에 대한 비 정적 setter;
  2. org.springframework.beans.factory.config.MethodInvokingFactoryBean정적 setter를 호출하는 데 사용 합니다.

첫 번째 옵션에는 일반 setter가있는 Bean이 있지만 인스턴스 속성을 설정하는 대신 정적 속성 / 필드를 설정합니다.

public void setTheProperty(Object value) {
    foo.bar.Class.STATIC_VALUE = value;
}

그러나이를 수행하려면이 setter를 노출 할 빈 인스턴스가 있어야합니다 ( 해결 방법 과 비슷 함 ).

두 번째 경우에는 다음과 같이 수행됩니다.

<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="staticMethod" value="foo.bar.Class.setTheProperty"/>
    <property name="arguments">
        <list>
            <ref bean="theProperty"/>
        </list>
   </property>
</bean>

당신의 경우 Utils클래스 에 새로운 setter를 추가합니다 .

public static setDataBaseAttr(Properties p)

그리고 당신의 맥락에서 당신은 위에 예시 된 접근 방식으로 구성 할 것입니다.

<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="staticMethod" value="foo.bar.Utils.setDataBaseAttr"/>
    <property name="arguments">
        <list>
            <ref bean="dataBaseAttr"/>
        </list>
   </property>
</bean>

비슷한 요구 사항이 있습니다. Spring 관리 저장소 빈을 Person엔티티 클래스 에 삽입해야했습니다 (예 : JPA 엔티티와 같이 "신원이있는 것"에서와 같이 "엔티티"). Person인스턴스는 친구를 가지고 있으며,이를 위해 Person인스턴스가 친구를 반환, 거기 친구의 저장소 및 쿼리에 위임된다.

@Entity
public class Person {
    private static PersonRepository personRepository;

    @Id
    @GeneratedValue
    private long id;

    public static void setPersonRepository(PersonRepository personRepository){
        this.personRepository = personRepository;
    }

    public Set<Person> getFriends(){
        return personRepository.getFriends(id);
    }

    ...
}

.

@Repository
public class PersonRepository {

    public Person get Person(long id) {
        // do database-related stuff
    }

    public Set<Person> getFriends(long id) {
        // do database-related stuff
    }

    ...
}

So how did I inject that PersonRepository singleton into the static field of the Person class?

I created a @Configuration, which gets picked up at Spring ApplicationContext construction time. This @Configuration gets injected with all those beans that I need to inject as static fields into other classes. Then with a @PostConstruct annotation, I catch a hook to do all static field injection logic.

@Configuration
public class StaticFieldInjectionConfiguration {

    @Inject
    private PersonRepository personRepository;

    @PostConstruct
    private void init() {
        Person.setPersonRepository(personRepository);
    }
}

As these answers are old, this is one I liked and is very clean that works with just java annotations:

To fix it, create a “none static setter” to assign the injected value for the static variable. For example :

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class GlobalValue {

public static String DATABASE;

@Value("${mongodb.db}")
public void setDatabase(String db) {
    DATABASE = db;
}
}

https://www.mkyong.com/spring/spring-inject-a-value-into-static-variables/

참고URL : https://stackoverflow.com/questions/11324372/how-to-make-spring-inject-value-into-a-static-field

반응형