Home > Java > javaTutorial > body text

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

WBOY
Release: 2023-05-12 13:31:06
forward
1110 people have browsed it

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!

Related labels:
source:yisu.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template