search
HomeJavajavaTutorialWhat is Spring's simple way to read and store objects in Java?

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:

What is Spring's simple way to read and store objects in Java?

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.

What is Spring's simple way to read and store objects in Java?

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.

What is Spring's simple way to read and store objects in Java?

  • 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.

What is Spring's simple way to read and store objects in Java?

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.

@Controller
public class StudentController {
    @Resource 
    private StudentService studentService;

    public void sayHi() {
        // 调用 service 方法
        studentService.sayHi();
    }
}
@Autowired Differences from @Resource

Same points: both are used to implement dependency injection.

Differences:

  • 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.

Multiple @Bean error handling of the same type
When the following multiple beans appear and return the same object type, the program will report an error

What is Spring's simple way to read and store objects in Java?

At this time we Run:

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 type

There 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!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

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

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

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

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

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

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

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]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SecLists

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

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool