search
HomeJavajavaTutorialSpring Ioc-detailed introduction to several methods of dependency injection

A setter method injection

The configuration file is as follows:

<bean id="helloAction" class="org.yoo.action.SpringSetterHelloAction">
<!-- setter injection using the nested <ref/> element -->
<property name="helloservice"><ref bean="helloService"/></property>
<!--可以不设置类型 -->
<property name="name" value="yoo"></property>
</bean>

The code in the action implementation class:

private IHelloService helloservice;private String name ;
public void sayHello(){helloservice.sayHello();
System.out.println(this.name);}
public void setHelloservice(IHelloService helloservice) {this.helloservice = helloservice;}
public void setName(String name) {this.name = name;}

here Both name and helloservice are injected using the property's setter method. That is, set a global property in the class and have a setter method for the property for container injection.

2 Constructor injection

spring also supports constructor injection, that is, constructor or constructor injection in some data.

Look at the configuration file first:

<!--普通构造器注入-->
<bean id="helloAction" class="org.yoo.action.ConstructorHelloAction">
<!--type 必须为Java.lang.String 因为是按类型匹配的,不是按顺序匹配-->
<constructor-arg type="java.lang.String" value="yoo"/>
<!-- 也可以使用index来匹配-->
<!--<constructor-arg index="1" value="42"/>-->
<constructor-arg><ref bean="helloService"/>
</constructor-arg>
</bean>

The code in the action implementation class:

private HelloServiceImpl helloservice;
private String name ;
public SpringConstructorHelloAction(HelloServiceImpl helloservice,String name){this.helloservice = helloservice;
this.name = name ;}
@Overridepublic void sayHello() {helloservice.sayHello();
System.out.println(this.name);}

Set 2 attributes as well, and then inject them in the constructor.

Three static factory injection

The configuration file is as follows:

<!--静态工厂构造注入-->
<!--注意这里的class 带factory-method参数-->
<!--factory-method的值是FactoryHelloAction中的工厂方法名createInstance-->
<bean id="helloAction" class="org.yoo.di.FactoryHelloAction" factory-method="createInstance">
<constructor-arg type="java.lang.String" value="yoo"/>
<constructor-arg>
<ref bean="helloService"/>
</constructor-arg>
</bean>

action implementation class:

private HelloServiceImpl helloservice;
private String name = null;
private SpringFactoryHelloAction(String name ,HelloServiceImpl helloservice){this.helloservice = helloservice ;
this.name = name ;}
public static SpringFactoryHelloAction createInstance(String name ,HelloServiceImpl helloservice) 
{SpringFactoryHelloAction fha = new SpringFactoryHelloAction (name,helloservice);
// some other operationsreturn fha;}
@Overridepublic void sayHello() 
{helloservice.sayHello();
System.out.println(this.name);}

Four no configuration File injection (automatic injection)

The above three methods require writing configuration files. In spring 2.5, an ioc implementation without writing configuration files is also provided. It should be noted that no configuration file refers to dependencies between beans and is not based on configuration files, but does not mean that there is no spring configuration file.

The configuration file is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.php.cn/">
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<bean id="helloService" class="org.yoo.service.HelloServiceImpl">
</bean>
<bean id="helloAction" class="org.yoo.action.AutowiredHelloAction">
</bean>
</beans>

It can be seen that the above only sets the two beans helloService and helloAction, and does not set the dependence of helloAction on helloService.

In addition, is required to support automatic injection.

Action implementation class:

/*
* 属性自动装载
*/
/*
@Autowired
private HelloService helloservice;
@Override
public void sayHello() {
helloservice.sayHello();
。

The above code is very simple. Add @Autowired annotation to the attribute, and spring will automatically inject HelloService.

Also supports the injection of constructors and setter methods, as follows:

Automatic injection of constructors:

/*
* 还可以使用构造函数设置
*/
@Autowired
public SpringAutowiredHelloAction(HelloServiceImpl helloservice){
this.helloservice = helloservice;
}

Automatic injection of setter methods:

/*
* 也可以使用set方法设置
*/
/*
@Autowired
public void setHelloservice(HelloService helloservice) {
this.helloservice = helloservice;
}

Finally, it is mentioned in the spring reference document that if you do not use automatic injection, try to use the setter method. Generally, the setter method is also used.

Whether to use automatic injection or the configuration file method, if jdk is lower than 1.5 or spring is not 2.5, you can only use the configuration file method. The rest depends on the actual project selection.

The above is the detailed introduction of several methods of Spring Ioc-dependency injection. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does the JVM manage garbage collection across different platforms?How does the JVM manage garbage collection across different platforms?Apr 28, 2025 am 12:23 AM

JVMmanagesgarbagecollectionacrossplatformseffectivelybyusingagenerationalapproachandadaptingtoOSandhardwaredifferences.ItemploysvariouscollectorslikeSerial,Parallel,CMS,andG1,eachsuitedfordifferentscenarios.Performancecanbetunedwithflagslike-XX:NewRa

Why can Java code run on different operating systems without modification?Why can Java code run on different operating systems without modification?Apr 28, 2025 am 12:14 AM

Java code can run on different operating systems without modification, because Java's "write once, run everywhere" philosophy is implemented by Java virtual machine (JVM). As the intermediary between the compiled Java bytecode and the operating system, the JVM translates the bytecode into specific machine instructions to ensure that the program can run independently on any platform with JVM installed.

Describe the process of compiling and executing a Java program, highlighting platform independence.Describe the process of compiling and executing a Java program, highlighting platform independence.Apr 28, 2025 am 12:08 AM

The compilation and execution of Java programs achieve platform independence through bytecode and JVM. 1) Write Java source code and compile it into bytecode. 2) Use JVM to execute bytecode on any platform to ensure the code runs across platforms.

How does the underlying hardware architecture affect Java's performance?How does the underlying hardware architecture affect Java's performance?Apr 28, 2025 am 12:05 AM

Java performance is closely related to hardware architecture, and understanding this relationship can significantly improve programming capabilities. 1) The JVM converts Java bytecode into machine instructions through JIT compilation, which is affected by the CPU architecture. 2) Memory management and garbage collection are affected by RAM and memory bus speed. 3) Cache and branch prediction optimize Java code execution. 4) Multi-threading and parallel processing improve performance on multi-core systems.

Explain why native libraries can break Java's platform independence.Explain why native libraries can break Java's platform independence.Apr 28, 2025 am 12:02 AM

Using native libraries will destroy Java's platform independence, because these libraries need to be compiled separately for each operating system. 1) The native library interacts with Java through JNI, providing functions that cannot be directly implemented by Java. 2) Using native libraries increases project complexity and requires managing library files for different platforms. 3) Although native libraries can improve performance, they should be used with caution and conducted cross-platform testing.

How does the JVM handle differences in operating system APIs?How does the JVM handle differences in operating system APIs?Apr 27, 2025 am 12:18 AM

JVM handles operating system API differences through JavaNativeInterface (JNI) and Java standard library: 1. JNI allows Java code to call local code and directly interact with the operating system API. 2. The Java standard library provides a unified API, which is internally mapped to different operating system APIs to ensure that the code runs across platforms.

How does the modularity introduced in Java 9 impact platform independence?How does the modularity introduced in Java 9 impact platform independence?Apr 27, 2025 am 12:15 AM

modularitydoesnotdirectlyaffectJava'splatformindependence.Java'splatformindependenceismaintainedbytheJVM,butmodularityinfluencesapplicationstructureandmanagement,indirectlyimpactingplatformindependence.1)Deploymentanddistributionbecomemoreefficientwi

What is bytecode, and how does it relate to Java's platform independence?What is bytecode, and how does it relate to Java's platform independence?Apr 27, 2025 am 12:06 AM

BytecodeinJavaistheintermediaterepresentationthatenablesplatformindependence.1)Javacodeiscompiledintobytecodestoredin.classfiles.2)TheJVMinterpretsorcompilesthisbytecodeintomachinecodeatruntime,allowingthesamebytecodetorunonanydevicewithaJVM,thusfulf

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft