Home Java javaTutorial Spring Ioc-detailed introduction to several methods of dependency injection

Spring Ioc-detailed introduction to several methods of dependency injection

Mar 03, 2017 am 10:15 AM

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>
Copy after login

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;}
Copy after login

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>
Copy after login

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);}
Copy after login

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>
Copy after login

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);}
Copy after login

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>
Copy after login

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();
。
Copy after login

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;
}
Copy after login

Automatic injection of setter methods:

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

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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

A new programming paradigm, when Spring Boot meets OpenAI A new programming paradigm, when Spring Boot meets OpenAI Feb 01, 2024 pm 09:18 PM

In 2023, AI technology has become a hot topic and has a huge impact on various industries, especially in the programming field. People are increasingly aware of the importance of AI technology, and the Spring community is no exception. With the continuous advancement of GenAI (General Artificial Intelligence) technology, it has become crucial and urgent to simplify the creation of applications with AI functions. Against this background, "SpringAI" emerged, aiming to simplify the process of developing AI functional applications, making it simple and intuitive and avoiding unnecessary complexity. Through "SpringAI", developers can more easily build applications with AI functions, making them easier to use and operate.

Use Spring Boot and Spring AI to build generative artificial intelligence applications Use Spring Boot and Spring AI to build generative artificial intelligence applications Apr 28, 2024 am 11:46 AM

As an industry leader, Spring+AI provides leading solutions for various industries through its powerful, flexible API and advanced functions. In this topic, we will delve into the application examples of Spring+AI in various fields. Each case will show how Spring+AI meets specific needs, achieves goals, and extends these LESSONSLEARNED to a wider range of applications. I hope this topic can inspire you to understand and utilize the infinite possibilities of Spring+AI more deeply. The Spring framework has a history of more than 20 years in the field of software development, and it has been 10 years since the Spring Boot 1.0 version was released. Now, no one can dispute that Spring

What are the implementation methods of spring programmatic transactions? What are the implementation methods of spring programmatic transactions? Jan 08, 2024 am 10:23 AM

How to implement spring programmatic transactions: 1. Use TransactionTemplate; 2. Use TransactionCallback and TransactionCallbackWithoutResult; 3. Use Transactional annotations; 4. Use TransactionTemplate in combination with @Transactional; 5. Customize the transaction manager.

How to set transaction isolation level in Spring How to set transaction isolation level in Spring Jan 26, 2024 pm 05:38 PM

How to set the transaction isolation level in Spring: 1. Use the @Transactional annotation; 2. Set it in the Spring configuration file; 3. Use PlatformTransactionManager; 4. Set it in the Java configuration class. Detailed introduction: 1. Use the @Transactional annotation, add the @Transactional annotation to the class or method that requires transaction management, and set the isolation level in the attribute; 2. In the Spring configuration file, etc.

Spring Annotation Revealed: Analysis of Common Annotations Spring Annotation Revealed: Analysis of Common Annotations Dec 30, 2023 am 11:28 AM

Spring is an open source framework that provides many annotations to simplify and enhance Java development. This article will explain commonly used Spring annotations in detail and provide specific code examples. @Autowired: Autowired @Autowired annotation can be used to automatically wire beans in the Spring container. When we use the @Autowired annotation where dependencies are required, Spring will find matching beans in the container and automatically inject them. The sample code is as follows: @Auto

Detailed explanation of Bean acquisition methods in Spring Detailed explanation of Bean acquisition methods in Spring Dec 30, 2023 am 08:49 AM

Detailed explanation of the Bean acquisition method in Spring In the Spring framework, Bean acquisition is a very important part. In applications, we often need to use dependency injection or dynamically obtain instances of beans. This article will introduce in detail how to obtain beans in Spring and give specific code examples. Obtaining the Bean@Component annotation through the @Component annotation is one of the commonly used annotations in the Spring framework. We can do this by adding @Compone on the class

Spring Security permission control framework usage guide Spring Security permission control framework usage guide Feb 18, 2024 pm 05:00 PM

In back-end management systems, access permission control is usually required to limit different users' ability to access interfaces. If a user lacks specific permissions, he or she cannot access certain interfaces. This article will use the waynboot-mall project as an example to introduce how common back-end management systems introduce the permission control framework SpringSecurity. The outline is as follows: waynboot-mall project address: https://github.com/wayn111/waynboot-mall 1. What is SpringSecurity? SpringSecurity is an open source project based on the Spring framework, aiming to provide powerful and flexible security for Java applications.

Application of JUnit unit testing framework in Spring projects Application of JUnit unit testing framework in Spring projects Apr 18, 2024 pm 04:54 PM

JUnit is a widely used Java unit testing framework in Spring projects and can be applied by following steps: Add JUnit dependency: org.junit.jupiterjunit-jupiter5.8.1test Write test cases: Use @ExtendWith(SpringExtension.class) to enable extension, use @Autowired inject beans, use @BeforeEach and @AfterEach to prepare and clean, and mark test methods with @Test.

See all articles