Spring @ Autowired 개인 속성 주석 (set 방법 없 음)
예전 에 이해 한 의존 주입 에 따라 주입 점 이 필요 합 니 다. set 방법 일 수도 있 고 구조 방법 일 수도 있 습 니 다. 그러나 이 속성 은 외부 access 를 통 해 주입 할 수 있 는 방법 이 없습니다. 그 는 어떻게 주입 합 니까?
인터넷 에서 한 번 검색 해 보 니 답 은 다음 과 같다.
stackoverflow.com/questions/4127365/how-can-spring-hibernate-access-private-members/4127403#4127403
You can set private a variable of another object through reflection. Here is an example on how to do it. Consider the following object with a private variable:
1
2
3
public
class
MyBean {
private
String
message;
}
Normally the message field wouldn't be accessible from outside MyBean, however, SnoopyClass can set and get its value. I wrote two static methods:
setValue
which can set a value into a private field called fieldName of an Object bean and a getValue
method which can get the value of a private variable called fieldName from an Object bean. The main method just demonstrates its use by creating an Object of MyBean class, setting the message variable and retrieving it. I've actually tested this code as a standalone application and it works.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import
java.lang.reflect.Field;
public
class
SnoopyClass {
private
static
void
setValue(
Object
bean,
String
fieldName,
Object
value)
throws IllegalArgumentException, IllegalAccessException,
SecurityException, NoSuchFieldException {
Field privateVar = bean.getClass().getDeclaredField(fieldName);
privateVar.setAccessible(
true
);
privateVar.
set
(bean, value);
}
private
static
Object
getValue(
Object
bean,
String
fieldName)
throws IllegalArgumentException, IllegalAccessException,
SecurityException, NoSuchFieldException {
Field privateVar = bean.getClass().getDeclaredField(fieldName);
privateVar.setAccessible(
true
);
return
privateVar.
get
(bean);
}
public
static
void
main(
String
[] argv)
throws IllegalArgumentException, SecurityException,
IllegalAccessException, NoSuchFieldException {
MyBean instance =
new
MyBean();
setValue(instance,
"message"
,
"Shht! Don't tell anyone!"
);
System.out.println(
"The message is '"
+ getValue(instance,
"message"
));
}
}
The implementation uses
getDeclaredField
method on the class of the Object, because this method can look for all fields, even private. In contrast, getField
can only access public members. The next step is calling setAccessible
on the field to allow reading and writing it. The last step, is simply use the get
and set
methods provided by the java.lang.reflect.Field
class. This kind of manipulation is allowed only if the security manager allows that. By default Java doesn't install any security manager, so in a standalone program that you launch through your IDE or the command line, you won't have any problems to use this technique. I've also tried, in a Spring Application under Tomcat, and it's still working.
The primary application, at least for me, is being able to set private variables in my unit tests, especially for Spring Beans, without polluting the interface with unneeded setters.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.