스프링 주입값을 정적 장으로 만드는 방법
이것이 이전에 질문했던 것처럼 보일 수도 있다는 것을 알고 있지만 여기서는 다른 문제에 직면해 있습니다.
정적인 방법만 있는 유틸리티 클래스가 있습니다.저는 그러지도 않고, 그것에 대해 예를 들지도 않을 것입니다.
public class Utils{
private static Properties dataBaseAttr;
public static void methodA(){
}
public static void methodB(){
}
}
이제 DatabaseAttributes Properties로 dataBaseAttributes를 채우려면 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이기 때문에 나는 여전히 변수를 사용할 수 없습니다.
두 가지 가능성이 있습니다.
- 정적 속성/필드에 대한 비정적 설정기
- 정적 설정기를 호출하는 데 사용합니다.
첫 번째 옵션에서는 고정 속성/필드를 설정하는 대신 일반 설정기가 있는 빈이 있습니다.
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>
당신의 경우 당신은 에 새로운 setter를 추가할 것입니다.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>
저도 비슷한 요구사항이 있었습니다.스프링 관리 저장소 콩을 내 것에 주입해야 했습니다.Person엔티티 클래스("정체성을 가진 무언가"에 있는 엔티티", 예를 들어 JPA 엔티티). A.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
}
...
}
그럼 어떻게 주입한 거지?PersonRepository정적 필드에 싱글톤을 입력합니다.Person수업?
제가 만든 것은.@Configuration, Spring ApplicationContext 구축 시간에 픽업됩니다.이것.@Configuration다른 반에 정적 필드로 주입해야 하는 콩을 모두 주입합니다.그다음에.@PostConstruct주석, 나는 모든 정적 필드 주입 로직을 수행하기 위해 후크를 잡습니다.
@Configuration
public class StaticFieldInjectionConfiguration {
@Inject
private PersonRepository personRepository;
@PostConstruct
private void init() {
Person.setPersonRepository(personRepository);
}
}
이 답변들이 오래된 만큼, 저는 이 대안으로 찾았습니다.이것은 매우 깨끗하고 자바 주석만으로 작동합니다.
이를 수정하려면 "none static setter"를 생성하여 static 변수에 주입된 값을 할당합니다.예를 들어 다음과 같습니다.
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
'programing' 카테고리의 다른 글
| 업데이트를 위한 mariadb가 올바르게 작동하지 않습니다. (0) | 2023.09.06 |
|---|---|
| Oracle 10g에서 ROW_MOVEMENT를 활성화/비활성화하면 어떤 영향을 받습니까? (0) | 2023.09.06 |
| 3.0 데이터를 문자열로 신속하게 이동할 수 있습니까? (0) | 2023.09.06 |
| 특정 줄을 무시할 수 있습니까? (0) | 2023.09.06 |
| '노드'라는 용어를 인식할 수 없습니다...인 파워셸 (0) | 2023.09.06 |