Table of Contents
Differences and usage scenarios of different Bean annotations
What is a Bean?
SpringBoot的各种注解
@Configuration
Home Java javaTutorial What are the differences and usage scenarios of different Bean annotations in SpringBoot?

What are the differences and usage scenarios of different Bean annotations in SpringBoot?

May 12, 2023 pm 01:31 PM
bean springboot

Differences and usage scenarios of different Bean annotations

What is a Bean?

The subtext of talking about Bean is to talk about Bean in Spring. We all know the BeanFactory in Spring, and the concept of Bean comes from this. In Spring, as long as a class can be instantiated and managed by the Spring container, this class is called a Bean, or SpringBean.

In addition, we also heard some other words:

JavaBean, POJO, VO, DTO

What do these names mean? What is the usage scenario?

JavaBean

A JavaBean is a class that follows Sun's JavaBean specification. JavaBean can be understood as a reusable component in java, which meets the following conditions:

  • There is a public default construction method

  • This The attributes of the class are accessed using getters and setters, and the naming follows the standard convention

  • This class can be serialized

##POJO( Plain Ordinary Object )

POJO is a historical name. Why do you say this? Because POJO is used to indicate that the object is different from Entity Beans

EntityBeans is a concept in EJB, and EJB gradually faded out of the stage of history after the emergence of Spring. Therefore, when POJO was proposed by Martin Fowler, it referred to ordinary Java classes that did not implement any EJB interface. As it continues to be used today, strictly speaking, all Java classes are POJOs, because no one is using old antiques like ejb anymore. But sometimes in order to distinguish Spring Beans, we can call classes that are not managed by Spring POJO.

VO (Value Object)

VO refers to an object such as java.lang.Integer which holds some data, or a data object. This concept is a concept proposed by Martin Fowler in Enterprise Application Architecture.

DTO (Data Transfer Object)

DTO is also a concept proposed by EJB. The purpose is to transmit data in the network by directly transmitting objects during data transmission. .

Summary:

So for us, there is no difference between VO and DTO (but Martin Fowler may have used them to express different segmentation concepts), while most At the same time, they follow the JavaBean specification, so they are also JavaBeans. Of course, they are all POJOs.

It can be seen that they essentially refer to a java object. In order to distinguish scenarios and functions, they have different names. Entity, Domain, etc. sometimes appear during development. Used to represent the mapping of entities or tables. Generally, you can do this to standardize development:

  • For objects managed by Spring, it is called Bean

  • The object entity class mapped to the data table, Called entity, placed in the entity directory

  • For the interface, it is used to encapsulate data, such as accepting a json input parameter. For convenience, define an object encapsulation parameter, which can be called dto (or pojo) Put it in the pojo package to indicate that it is not a mapping class for a certain table.

What is the difference between annotations @Bean @Component...etc.?

When developing applications with SpringBoot, we will use annotations to hand over objects to the Spring container for management. These annotations include:

@Component, @Service, @Bean, @Controller, @Repository

These annotations are essentially Spring identifiers and are used for automatic detection of beans. Classes marked with these annotations will be managed by the Spring container.

So why are there these categories? Why not use an annotation to do all the work?

First of all, these annotations are used at different levels based on semantics

  • @ComponentGeneral components

  • @Service is a Service layer component

  • @BeanThis should be used together with @Configuration, which will be discussed later

  • @Controller is used in the SpringMVC control layer

  • @Repository is the data access layer

Spring is designed this way because these annotations are not only for automatic detection. At the same time, there are different functions, such as @Repository annotation, Spring will add enhanced processing and related exception handling.

@Controller’s bean will handle network request related logic. So if you mark the same annotation on all beans, they will indeed be injected into the Spring container, but the function may not work.

And as the Spring version is upgraded, more differentiated processing may be added. So we should annotate according to the specifications.

Speaking of @Bean, we know that in the early days of Spring, Beans were still configured through xml. For example:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd 
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context.xsd">
     
    <bean id="operations"    class="com.howtodoinjava.spring.beans.Operations"></bean>
    <bean id="employee"  class="com.howtodoinjava.spring.beans.Employee"></bean>
     
</beans>
Copy after login

Now, you can understand that the class annotated with @Configuration is an xml configuration file, and the @Bean annotation in the middle It is the bean node in xml

@Configuration
public class BeanConfiguration {
     @Bean
     public Operations operation(){
         return new Operations();
     }
     @Bean
     public Employee employee(){
         return new Employee();
     }
    
}
Copy after login

Both methods inject the @Bean annotation return value into the Spring container. When SpringBoot starts, it will scan the @Configuration annotation and inject it.

How to resolve SpringBoot injection object conflicts?

Okay, now we finally hand over the desired components to the Spring container management. How should we use it?

We can use Spring context to get the required objects

public static void main(String[] args) {
        ApplicationContext application = SpringApplication.run(ConsumerApplication.class, args);
        application.getBean(Employee.class);
}
Copy after login

Generally we use @Autowire annotation to get the beans in the container

@Autowire
private Employee employee;
Copy after login

Sometimes we need to inject a container into the container Multiple instances of the class to suit the needs.

比如一个接口的实现类有两个,如果直接通过@Component注入容器,则会报错。

如何区分?

@Component("bean01")
public class Bean01 implement AA{
    
}

@Component("bean02")
public class Bean02 implement AA{
    
}
Copy after login

没错,通过在注解中标识一个名称,来区分该对象的不同实例。

获取时:最终会初始化一个Bean01

@Autowire
@Qualifier("bean01")
private AA a;
Copy after login

这样有个问题,就是每次使用都需要显示声明@Qualifier来指定。有的场景下,我们可能想默认使用一个,其他情况再显式指定。这就涉及到@Primary

在注解时,标注了@Primary的Bean在没有指定的情况下,会默认加载。

比如:

@Component
@Primary
public class Bean01 implement AA{
    
}

@Component("bean02")
public class Bean02 implement AA{
    
}
Copy after login

使用时: 默认初始化的就是Bean01

@Autowire
private AA a;
Copy after login

SpringBoot的各种注解

@Configuration

表示当前类可以用作配置文件使用

可以在这个类中使用@bean注解来创建对象(类似于单例模式的饿汉式)。

方法中需要有返回值+使用new这个关键字

spring会把这个返回值放入spring容器中;

在后面的方法中如果要调用这个方法(@bean中有个属性name,命名name的值,在后面的@resource中使用使用按照名称注入)没有使用name这个属性的话,默认情况下@bean方法的方法名;

  • @importResource:用来导入xml文件,xml文件里面也是声明java对象,同样也是导入到spring容器中

  • @propertySource:用来导入property文件

可以和@value一起使用,@value来用读取property文件的内容;

  • @componentScan:用来指定扫描注解的位置,扫描把扫描到的注解生成对象放入spring容器中,

属性:basePackage:指定扫描到包的位置

默认情况下是扫描当前包和子包的位置

  • @SpringBootApplication

由三个主要注解组合而成:@SpringBootConfiguration+@EnableAutoConfiguration+@ComponentScan

  • @SpringBootCOnfiguration:表示这个类可以作为配置类使用;

  • @EnableAutoConfiguration:启动自动注入,把java文件配置好,直接注入到Spring容器中;

  • @ComponentScan:表示文件下的注解,用来创建对象

  • @ConfigurationProperties:使用在java类上,表示使用K-V自动注入到对应的java属性上,

参数prefix:把properties文件中对应的前缀.后面的属性对应到properties文件的属性中(使用在类上,所以在属性上可以自动赋值)

和@value是两种用法

@controller、@service、@Repository、@component

这些注解使用在java类上,componentScan会扫描这些完成对象的创建

  • @controller使用在控制层,完成接收请求参数,调用service层完成用户的请求,返回视图层给用户;

  • @Service:业务层的逻辑,调用dao层完成用户对数据库的操作,将处理结果返回给controller;

  • @Repository:使用对数据库进行持久化操作(保证用户的数据可以写入到数据库中),将处理结果返回给service层

##在SpringBoot中使用@mapper代替这个注解。用来告诉mybatis创建这个对象的动态代理对象

##@mapperScan(basePackage:指定的mapper文件的路径),使用在主启动类上,省的一个一个dao层都要使用到@mapper

  • @component:用来创建对象,但是对象没有前面三个有特殊的功能

  • @transaction:表示开启事务(一般使用在service层)有五个参数

1、传播行为 2、隔离级别 3、超时行为 4、回滚规则 5、是否只读

@RestController   = @responseBody+@controller
Copy after login

使用在类上:表示这个类是控制层,而且类中的所有方法加上@responseBody这个注解

The above is the detailed content of What are the differences and usage scenarios of different Bean annotations in SpringBoot?. For more information, please follow other related articles on the PHP Chinese website!

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

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

How Springboot integrates Jasypt to implement configuration file encryption How Springboot integrates Jasypt to implement configuration file encryption Jun 01, 2023 am 08:55 AM

Introduction to Jasypt Jasypt is a java library that allows a developer to add basic encryption functionality to his/her project with minimal effort and does not require a deep understanding of how encryption works. High security for one-way and two-way encryption. , standards-based encryption technology. Encrypt passwords, text, numbers, binaries... Suitable for integration into Spring-based applications, open API, for use with any JCE provider... Add the following dependency: com.github.ulisesbocchiojasypt-spring-boot-starter2. 1.1Jasypt benefits protect our system security. Even if the code is leaked, the data source can be guaranteed.

How to use Redis to implement distributed locks in SpringBoot How to use Redis to implement distributed locks in SpringBoot Jun 03, 2023 am 08:16 AM

1. Redis implements distributed lock principle and why distributed locks are needed. Before talking about distributed locks, it is necessary to explain why distributed locks are needed. The opposite of distributed locks is stand-alone locks. When we write multi-threaded programs, we avoid data problems caused by operating a shared variable at the same time. We usually use a lock to mutually exclude the shared variables to ensure the correctness of the shared variables. Its scope of use is in the same process. If there are multiple processes that need to operate a shared resource at the same time, how can they be mutually exclusive? Today's business applications are usually microservice architecture, which also means that one application will deploy multiple processes. If multiple processes need to modify the same row of records in MySQL, in order to avoid dirty data caused by out-of-order operations, distribution needs to be introduced at this time. The style is locked. Want to achieve points

How SpringBoot integrates Redisson to implement delay queue How SpringBoot integrates Redisson to implement delay queue May 30, 2023 pm 02:40 PM

Usage scenario 1. The order was placed successfully but the payment was not made within 30 minutes. The payment timed out and the order was automatically canceled. 2. The order was signed and no evaluation was conducted for 7 days after signing. If the order times out and is not evaluated, the system defaults to a positive rating. 3. The order is placed successfully. If the merchant does not receive the order for 5 minutes, the order is cancelled. 4. The delivery times out, and push SMS reminder... For scenarios with long delays and low real-time performance, we can Use task scheduling to perform regular polling processing. For example: xxl-job Today we will pick

How to solve the problem that springboot cannot access the file after reading it into a jar package How to solve the problem that springboot cannot access the file after reading it into a jar package Jun 03, 2023 pm 04:38 PM

Springboot reads the file, but cannot access the latest development after packaging it into a jar package. There is a situation where springboot cannot read the file after packaging it into a jar package. The reason is that after packaging, the virtual path of the file is invalid and can only be accessed through the stream. Read. The file is under resources publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

Comparison and difference analysis between SpringBoot and SpringMVC Comparison and difference analysis between SpringBoot and SpringMVC Dec 29, 2023 am 11:02 AM

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

How SpringBoot customizes Redis to implement cache serialization How SpringBoot customizes Redis to implement cache serialization Jun 03, 2023 am 11:32 AM

1. Customize RedisTemplate1.1, RedisAPI default serialization mechanism. The API-based Redis cache implementation uses the RedisTemplate template for data caching operations. Here, open the RedisTemplate class and view the source code information of the class. publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations, BeanClassLoaderAware{//Declare key, Various serialization methods of value, the initial value is empty @NullableprivateRedisSe

How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables Jun 02, 2023 am 11:07 AM

When Springboot+Mybatis-plus does not use SQL statements to perform multi-table adding operations, the problems I encountered are decomposed by simulating thinking in the test environment: Create a BrandDTO object with parameters to simulate passing parameters to the background. We all know that it is extremely difficult to perform multi-table operations in Mybatis-plus. If you do not use tools such as Mybatis-plus-join, you can only configure the corresponding Mapper.xml file and configure The smelly and long ResultMap, and then write the corresponding sql statement. Although this method seems cumbersome, it is highly flexible and allows us to

How to get the value in application.yml in springboot How to get the value in application.yml in springboot Jun 03, 2023 pm 06:43 PM

In projects, some configuration information is often needed. This information may have different configurations in the test environment and the production environment, and may need to be modified later based on actual business conditions. We cannot hard-code these configurations in the code. It is best to write them in the configuration file. For example, you can write this information in the application.yml file. So, how to get or use this address in the code? There are 2 methods. Method 1: We can get the value corresponding to the key in the configuration file (application.yml) through the ${key} annotated with @Value. This method is suitable for situations where there are relatively few microservices. Method 2: In actual projects, When business is complicated, logic

See all articles