2012-07-04 7 views
55

이전에 묻는 질문처럼 보일 수 있지만 다른 문제가 있습니다.정적 필드에 스프링 주입 값을 설정하는 방법

정적 메서드 만있는 유틸리티 클래스가 있습니다. 나는하지 않으며 나는 그것에서 예를 들어 가지 않을 것이다. 이미 다른 콩에서 일을하지만

<?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) 여기에 문제가되지 않습니다 : 내가 데이터베이스와 dataBaseAttr을 채우기 위해 봄을 필요로 지금

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

    } 

    public static void methodB(){ 

    } 
} 

는 Properties.Spring의 설정은 속성 그리고 만약 내가 bean을 아무것도 만들지 않는다면 클래스가 인스턴스화되지 않고 변수가 항상 null과 같기 때문에 변수를 사용할 수 없다.

답변

93

당신은 두 가지 가능성이 있습니다 정적 속성/필드

  1. 비 정적 세터;
  2. org.springframework.beans.factory.config.MethodInvokingFactoryBean을 사용하여 정적 설정기를 호출합니다.

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

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

하지만이 세터를 노출하는 콩 (그 이상과 같은 해결)의 인스턴스를 가질 필요가이 작업을 수행하기 위해

. 그것으로 수행 될 두 번째 경우

은 다음과 같습니다

<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 클래스에 새로운 세터를 추가합니다 케이스 :

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> 
+0

고마워, 당신은 정말 내 일 저장. –

+0

당신은 오신 것을 환영합니다! –

+0

나는 그것을 잘 이해하지 못했기 때문에 첫 번째 해결책을 시도하지 않았다. 제 2의 솔루션을 시도하고 잘됐다. –

20

나는 비슷한 요구 사항을 했어 : 내 Person 엔티티 클래스에 Spring 관리 저장소 빈을 주입하기 위해 필요 ("신원 뭔가"에서와 같이 "엔티티", 예를 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 
    } 

    ... 
} 

그래서 주입 않았다 어떻게 Person 클래스의 정적 필드에 PersonRepository 싱글인가요?

나는 Spring ApplicationContext 구축 시간에 픽업되어 @Configuration을 만들었습니다.이 @Configuration은 정적 필드로 다른 클래스에 주입해야하는 모든 빈을 주입합니다. 그런 다음 @PostConstruct 주석을 사용하여 모든 정적 필드 주입 논리를 수행 할 후크를 잡습니다.

@Configuration 
public class StaticFieldInjectionConfiguration { 

    @Inject 
    private PersonRepository personRepository; 

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

당신이 정적 메서드에서이 액세스 할 수있는 것이 가능되는 방법? 나는 이것이 가능하다고 전혀 믿지 않는다! 그것은 Person.personRepository = personRepository가 아니어야합니까? 그 @JonasGeiregat –

+3

이 방법은 정적이며 I는 사람이 정적 환경에서 '이'를 통해 정적 변수를 참조하는 방법 궁금 정적 변수 –

+3

액세스 될 때 가능? – Kripz

관련 문제