Spring simply reads and stores objects
Get the Bean object (object assembly)
Getting the bean object is also called object assembly, which is to take the object out and put it somewhere In classes, it is sometimes called object injection.
There are three ways to implement object assembly (object injection):
Attribute injection
Construction method Injection
Setter Injection
We first create the following packages and classes:
Attribute injection
Attribute injection is implemented using @Autowired
, and the Service class is injected into the Controller
class.
@Controller public class StudentController { // 1.使用属性注入的方式获取 Bean @Autowired private StudentService studentService; public void sayHi() { // 调用 service 方法 studentService.sayHi(); } }
Advantages:
Simple to implement and easy to use.
Disadvantages:
Functionality Problem: Unable to inject immutable (
final
) objects.
final objects (immutable) in Java Either assign the value directly or assign the value in the constructor, so when using attributes to inject a final object, it does not comply with the usage specifications of final in Java, so the injection cannot be successful.
Universality issue: Can only be adapted to
IoC
containers.Design principle issue: Easier Violates the single design principle. (For objects that are classes)
Single design principle:
For class level
For method level
Constructor method injection
Since Spring 4.x
, Spring official It is recommended to use the form of constructor injection.
@Controller public class StudentController { // 2.构造方法注入 private StudentService studentService; // @Autowired 可省略 @Autowired public StudentController(StudentService studentService) { this.studentService = studentService; } public void sayHi() { // 调用 service 方法 studentService.sayHi(); } }
# Note
#@Autowired
Can be omitted.But if there are multiple constructors in the class, you need to add
@Autowired
to clearly specify which constructor to use, otherwise the program An error will be reported.
Advantages:
Immutable objects can be injected.
The injected object will not be modified.
Added
final
modification symbol.The construction method is only executed once as the class is loaded.
The injected object will be fully initialized. (Use Advantages brought by the construction method)
Better versatility.
Disadvantages:
Without attribute injection, the implementation is simple.
Setter injection
Setter
Injection is similar to the Setter method implementation of the attribute, except that it needs to be added when setting the set method. @Autowired
Annotation.
@Controller public class StudentController { // 3.setter 注入 private StudentService studentService; @Autowired public void setStudentService(StudentService studentService) { this.studentService = studentService; } public void sayHi() { // 调用 service 方法 studentService.sayHi(); } }
Advantages:
is more in line with a single design principle. (Method level for objects)
Disadvantages:
Cannot inject immutable objects (
final
modified objects).- ## The injected object can be modified.
set The method is a normal set method and can be called repeatedly, with the risk of being modified.
Summary: In daily development, using attribute injection to achieve simpler reading of beans is still the mainstream implementation method.@Resource Keyword
When performing class injection, in addition to using the @Autowired keyword, we can also use @Resource for injection.@Autowired Differences from @ResourceSame points: both are used to implement dependency injection.Differences:@Controller public class StudentController { @Resource private StudentService studentService; public void sayHi() { // 调用 service 方法 studentService.sayHi(); } }
- Different functional support: @Autowired Supports property injection, setter injection, and constructor injection; @Resource only supports property injection and setter injection, and does not support constructor injection.
- Different origins: @Autowired comes from the Spring framework; and @Resource comes from JDK.
- Parameter support is different: @Resource supports more parameter settings; while @Autowired only supports required parameters.
public class App { public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-config.xml"); StudentController studentController = applicationContext.getBean("studentController", StudentController.class); studentController.func(); } }# Note# An error will be reported. The reason for the error is that it is a non-unique Bean object. Error handling for multiple beans of the same typeThere are two solutions to solve the problem of multiple beans of the same type:
- Use
@Resource(name="student1")
to define.
- Use
@Qualifier
to annotate the name.
#
使⽤ @Resource(name="student1")
定义.
@Controller public class StudentController { @Resource(name = "student2") private Student student; public void func() { System.out.println(student.toString()); } }
#
使⽤ @Qualifier
注解定义名称.
@Controller public class StudentController { @Resource @Qualifier("student2") private Student student; public void func() { System.out.println(student.toString()); } }
#
如果我们想用 @Autowired
可以写成:
@Autowired private Student student1; // 存在有耦合性问题
The above is the detailed content of What is Spring's simple way to read and store objects in Java?. For more information, please follow other related articles on the PHP Chinese website!

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool