Reflection mechanism and dependency injection of spring

Source: Internet
Author: User

We know that the reflection mechanism is widely used in spring, so where is it actually used?

A major core concept of spring is injection,

However, one premise of this is that the class is managed by spring.

Reflection generates a specific instance based on classname,

This is a very practical idea.

For example, when we need to select a specific implementation class based on the type of the passed parameter,

The reflection mechanism can solve the problem well.

However, we generally use the reflection mechanism. The created proxy class is instantiated Based on the constructor.

Instead of injecting data from the spring container.

This will lead to a problem where the injection function cannot be implemented in the created proxy class.

Of course, if you must use it, the system will prompt a null pointer error.

At this time, if the class created by reflection is injected by spring, this problem can be effectively solved.

This also has a problem.

Is to obtain the spring applicationcontext.

If we get it again,

This is a great waste of system resources.

In this way, we can declare a static variable to save applicationcontext.

// Declare a static variable to save
Public void setapplicationcontext (applicationcontext contex)
Throws beansexception {
Myapplicationcontextutil. Context = contex;
}

And manage it with the spring container.

In this way, we can easily obtain applicationcontext without consuming too much system resources.

Thus, it is very simple,

When all our implementation classes inherit the same interface,

Our interface can be initialized through reflection.

Create different implementation classes.

At the same time, because all classes are managed through spring.

Obviously, spring injection can also be used in the created implementation class.

Instead of empty pointer errors.

 

A reflection source class

We are very familiar with the concept of classes. For example, you can have the student class and the person class. But we need to know that there isClass classIs the source of reflection.

 

Normal Mode: Get the instantiated object through the complete Class Name> instantiate through new>

Reflection Method: instantiate the object-> getclass () method-> use the complete Class Name

 

A simple example:

 

Package CN. classes;

Public class oneclass {

}


Package CN. test;

Import CN. classes. oneclass;

Public class test {
Public static void main (string [] ARGs ){
Oneclass c = new oneclass ();
System. Out. println (C. getclass (). getname ());
}
}

Output result: CN. classes. oneclass


We need to use reflection to obtainClassThere are three methods:

Package CN. classes;

Public class oneclass {

}


Import CN. classes. oneclass;

Public class test {
Public static void main (string [] ARGs ){
Class <?> C1 = NULL;
Class <?> C2 = NULL;
Class <?> C3 = NULL;

Try
{
// Method 1: forname (important)
C1 = Class. forname ("cn. classes. oneclass ");
}
Catch (classnotfoundexception E)
{
E. printstacktrace ();
}
// Method 2
C2 = new oneclass (). getclass ();

// Method 3
C3 = oneclass. Class;

System. Out. println (c1.getname ());
System. Out. println (c2.getname ());
System. Out. println (c3.getname ());
}
}

Output result: CN. classes. oneclass

 

 

Ii. Use the class to instantiate the class

 

① Construction without Parameters

Package CN. classes;

Public class person {
Private string name;
Private int age;

.......... Omit getter, setter ..............

@ Override
Public String tostring ()
{
Return "person [name =" + name + ", age =" + age + "]";
}

}


Package CN. test;

Import CN. classes. person;

Public class test
{
// In this case, an empty constructor must exist in the class.
Public static void main (string [] ARGs)
{
Class <?> C = NULL;
Try
{
C = Class. forname ("cn. classes. person ");
Person P = (person) C. newinstance ();
P. setname ("XY ");
P. setage (20 );
System. Out. println (P );
}
Catch (exception E)
{
E. printstacktrace ();
}
}
}

 

② Construction with Parameters

Package CN. classes;

Public class person
{
Private string name;
Private int age;

.......... Omit getter, setter ..............

@ Override
Public String tostring ()
{
Return "person [name =" + name + ", age =" + age + "]";
}
}


Package CN. test;

Import java. Lang. Reflect. constructor;

Import CN. classes. person;

Public class test
{
// If no empty constructor exists
Public static void main (string [] ARGs)
{
Class <?> C = NULL;
Try
{
C = Class. forname ("cn. classes. person ");
Constructor <?> [] Cons = C. getconstructors ();
Person P = (person) Cons [0]. newinstance ("XY", 20 );
System. Out. println (P );
}
Catch (exception E)
{
E. printstacktrace ();
}
}
}

 

Iii. Use class instantiation in spring

Bean. xml
<Bean id = "ID" class = "com. XY. Student"/>

 

Spring will use code to create code Java instances
Class C = Class. forname ("com. XY. Student ");
Object bean = C. newinstance ();

 

 

Class call Methods

Package CN. classes;

Public class person
{
Public void add ()
{
System. Out. println ("add ");
}

Public void addwithparameters (string name, int age)
{
System. Out. println ("add method with Parameters" + name + age );
}
}


Package CN. test;

Import java. Lang. Reflect. method;

Public class test
{
Public static void main (string [] ARGs)
{
Class <?> C1 = NULL;
Try
{

C1 = Class. forname ("cn. classes. person ");

// Call a method without Parameters
Method M = c1.getmethod ("add ");
M. Invoke (c1.newinstance ());

 

// Call a method with Parameters
Method M1 = c1.getmethod ("addwithparameters", String. Class, Int. Class );
M1.invoke (c1.newinstance (), "XY", 22 );
}
Catch (exception E)
{
E. printstacktrace ();
}
}
}

 

 

Five classes get the getter and setter Methods

This class can obtain a lot of information about the class, such as the interface, constructor, attribute, and method of the class. Let's look at how to get the getter and setter methods.

Package CN. classes;

Public class person
{
Private string name;
Private int age;

Omit getter and setter

}

 

Package CN. test;

Import java. Lang. Reflect. method;

Public class test
{
Public static void main (string [] ARGs)
{
Class <?> C1 = NULL;
Object OBJ = NULL;
Try
{
C1 = Class. forname ("cn. classes. person ");
OBJ = c1.newinstance ();
Setter (OBJ, "name", "XY", String. Class );
Setter (OBJ, "Age", 20, Int. Class );
Getter (OBJ, "name ");
Getter (OBJ, "Age ");
}
Catch (exception E)
{
E. printstacktrace ();
}
}

/**
* @ Param OBJ: object to be operated
* @ Param Att: attribute to be operated
* @ Param value: attribute content to be set
* @ Param type: attribute type to be set
*/
Public static void setter (Object OBJ, string ATT, object value, class <?> Type)
{
Try
{
// Obtain the setter method.
Method M = obj. getclass (). getmethod ("set" + initstr (ATT), type );
M. Invoke (OBJ, value );
}
Catch (exception E)
{
E. printstacktrace ();
}
}

/**
* @ Param OBJ: object to be operated
* @ Param Att: attribute to be operated
*/
Public static void getter (Object OBJ, string ATT)
{
Try
{
// Obtain the getter method.
Method M = obj. getclass (). getmethod ("get" + initstr (ATT ));
System. Out. println (M. Invoke (OBJ ));
}
Catch (exception E)
{
E. printstacktrace ();
}
}

Public static string initstr (string oldstr)
{
String newstr = oldstr. substring (0, 1). touppercase () + oldstr. substring (1 );
Return newstr;
}
}

 

6. Spring calls the getter and setter Methods

Example of setter Injection

Bean. xml
<Bean id = "ID" class = "com. XY. Student">
<Property name = "stuname" value = "XY"/>
</Bean>


Spring will use the code to create a code Java instance and inject the value:
Class C = Class. forname ("com. XY. Student ");
Object bean = C. newinstance ();


Get the setter method name corresponding to stuname through some operations
String setname = "set" + "stuname ";
Method method = C. getmehod (setname, String. Class );
Method. Invoke (bean, "XY ");

This completes the most basic injection operations. Of course, spring can also be injected through constructors. In this way, refer to the use of class with parameter construction in the second point.

Class can also access annotation, so that the injection function can be completed when spring uses annotations.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.