Home Java javaTutorial Spring Framework Learning (2) Dependency Injection

Spring Framework Learning (2) Dependency Injection

Dec 29, 2016 pm 01:10 PM

The spring framework provides us with three injection methods, namely set injection, constructor injection, and interface injection. Interface injection is not required. The first two methods are introduced below.

1, set injection
Using the set method of the attribute to initialize it becomes set injection.
1) Assign values ​​to ordinary character types.

public class User{
   privateString username;
 
   publicString getUsername() {
       returnusername;
   }
   publicvoid setUsername(String username) {
      this.username= username;
   }
}
Copy after login

We only need to provide the set method of the attribute, and then go to the properties file to configure it so that the framework can find the beans tag of the applicationContext.xml file. Add bean tag to tag beans,
Specify id, class value, id value is not required, class value is the complete path where the object is located. Add the property
tag to the bean tag, requiring that the name value be consistent with the corresponding property name in the User class. The value value is the value we want to assign to the username attribute in the User class.

<bean id="userAction"class="com.lsz.spring.action.User" >
	<property name="username" value="admin"></property>
</bean>
Copy after login

2) Assign a value to the object
Also provide the set method of the object

public class User{
     private UserService userservice;
     public UserServicegetUserservice() {
          returnuser;
     }
     public void setUserservice(UserService userservice){
         this.userservice= userservice;
     }
}
Copy after login

In the configuration file, add the bean label declaration of UserService and the reference of the User object to UserService.

<!--对象的声明-->
<bean id="userService" class="com.lsz.spring.service.UserService"></bean>
 
<bean id="userAction"class="com.lsz.spring.action.User" >
   <property name="userservice" ref="userService"></property>
</bean>
Copy after login

With this configuration, the framework will inject the UserService object into the User class.

3) Assign values ​​to the list collection
Also provide the set method

public class User{
    privateList<String> username;
    publicList<String> getUsername() {
        returnusername;
    }
    publicvoid setUsername(List<String> username) {
        this.username= username;
    }
}
Copy after login
<bean id="userAction"class="com.lsz.spring.action.User" >
     <propertyname="username">
           <list>
               <value>zhang,san</value>
               <value>lisi</value>
               <value>wangwu</value>                                
               </list>
    </property>
</bean>
Copy after login

4) Assign values ​​to the fields in the properties file

public class User{
    privateProperties props ;
    publicProperties getProps() {
        returnprops;
    }
    publicvoid setProps(Properties props) {
        this.props= props;
    }
}
Copy after login
<bean>
    <propertyname="props">
        <props>
           <propkey="url">jdbc:oracle:thin:@localhost:orl</prop>
           <propkey="driverName">oracle.jdbc.driver.OracleDriver</prop>
           <propkey="username">scott</prop>
           <propkey="password">tiger</prop>
        </props>
    </property>
</bean>
Copy after login

key in the tag The value is the name in the .properties property file

Note:
No matter what value is assigned, the name attribute value of the tag in the configuration file must be consistent with the name in the object.


2 Constructor injection
1) One parameter of the constructor

public class User{
    privateString usercode;
    publicUser(String usercode) {
        this.usercode=usercode;
    }
}
Copy after login
<bean id="userAction"class="com.lsz.spring.action.User">                        
    <constructor-argvalue="admin"></constructor-arg>                        
</bean>
Copy after login

2) When the constructor has two parameters
When the parameter is a non-string type, The type needs to be specified in the configuration file. If the type is not specified, the value will be assigned as the string type.
When the parameter types are inconsistent, the framework searches according to the type of the string, so the location of the parameter needs to be specified in the configuration file

<constructor-argvalue="admin"index="0"></constructor-arg>                
<constructor-argvalue="23" type="int"index="1"></constructor-arg>
Copy after login

This is the first parameter in the constructor It is of string type, and the second parameter is of int type


## The above is the content of spring framework learning (2) 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)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1252
29
C# Tutorial
1226
24
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

Modify RequestBody in spring gateway Modify RequestBody in spring gateway Feb 09, 2024 pm 07:15 PM

I want to modify the requestbody before routing it to the given uri. Modify the body based on the documentation I'm using org.springframework.cloud.gateway.filter.factory.rewrite.modifyrequestbodygatewayfilterfactory. When starting my server, the server fails to start with the following error reason: Element [spring.cloud.gateway.routes[0].filters[0].modifyrequestbody.class] is not bound. \n\nOperation:\

How to use dependency injection (Dependency Injection) in the Phalcon framework How to use dependency injection (Dependency Injection) in the Phalcon framework Jul 30, 2023 pm 09:03 PM

Introduction to the method of using dependency injection (DependencyInjection) in the Phalcon framework: In modern software development, dependency injection (DependencyInjection) is a common design pattern aimed at improving the maintainability and testability of the code. As a fast and low-cost PHP framework, the Phalcon framework also supports the use of dependency injection to manage and organize application dependencies. This article will introduce you how to use the Phalcon framework

JAX-RS vs. Spring MVC: A battle between RESTful giants JAX-RS vs. Spring MVC: A battle between RESTful giants Feb 29, 2024 pm 05:16 PM

Introduction RESTful APIs have become an integral part of modern WEB applications. They provide a standardized approach to creating and using Web services, thereby improving portability, scalability, and ease of use. In the Java ecosystem, JAX-RS and springmvc are the two most popular frameworks for building RESTful APIs. This article will take an in-depth look at both frameworks, comparing their features, advantages, and disadvantages to help you make an informed decision. JAX-RS: JAX-RSAPI JAX-RS (JavaAPI for RESTful Web Services) is a standard JAX-RSAPI developed by JavaEE for developing REST

In-depth understanding of the architecture and working principles of the Spring framework In-depth understanding of the architecture and working principles of the Spring framework Jan 24, 2024 am 09:41 AM

An in-depth analysis of the architecture and working principles of the Spring framework Introduction: Spring is one of the most popular open source frameworks in the Java ecosystem. It not only provides a powerful set of container management and dependency injection functions, but also provides many other functions, such as transactions. Management, AOP, data access, etc. This article will provide an in-depth analysis of the architecture and working principles of the Spring framework, and explain related concepts through specific code examples. 1. Core concepts of the Spring framework 1.1IoC (Inversion of Control) Core of Spring

Optimizing program logging: Sharing tips on setting log4j log levels Optimizing program logging: Sharing tips on setting log4j log levels Feb 20, 2024 pm 02:27 PM

Optimizing program logging: Tips for setting log4j log levels Summary: Program logging plays a key role in troubleshooting, performance tuning, and system monitoring. This article will share tips on setting log4j log levels, including how to set different levels of logs and how to illustrate the setting process through code examples. Introduction: In software development, logging is a very important task. By recording key information during the running process of the program, it can help developers find out the cause of the problem and perform performance optimization and system monitoring.

Detailed explanation of Oracle database connection methods Detailed explanation of Oracle database connection methods Mar 08, 2024 am 08:45 AM

Detailed explanation of Oracle database connection methods In application development, database connection is a very important link, which carries the data interaction between the application and the database. Oracle database is a relational database management system with powerful functions and stable performance. In actual development, we need to be proficient in different connection methods to interact with Oracle database. This article will introduce in detail several common connection methods of Oracle database and provide corresponding code examples to help readers better understand and apply

Application of Java reflection mechanism in Spring framework? Application of Java reflection mechanism in Spring framework? Apr 15, 2024 pm 02:03 PM

Java reflection mechanism is widely used in Spring framework for the following aspects: Dependency injection: instantiating beans and injecting dependencies through reflection. Type conversion: Convert request parameters to method parameter types. Persistence framework integration: mapping entity classes and database tables. AspectJ support: intercepting method calls and enhancing code behavior. Dynamic Proxy: Create proxy objects to enhance the behavior of the original object.

See all articles