Use of Spring @Bean annotation

Instructions for use

This annotation is mainly used in methods, stating that the current method body contains the logic that eventually generates a bean instance, and the return value of the method is a bean . This bean will be added to the container for management by Spring. By default, the bean name is the method name using the bean annotation. @Bean is generally used with @Component or @Configuration.

@Bean Explicitly declare the correspondence between classes and beans, and allow users to create and configure bean instances according to actual needs.

This annotation is equivalent to:

<bean id="useService" class="com.test.service.UserServiceImpl"/>

Common components

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration
public class MyConfigration {
    @Bean
    public User user() {
        return new User;
    }
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
public class UserController {
    @Autowired
    User user;
 
    @GetMapping("/test")
    public User test() {
        return user.test();
    }
}

Named component

The bean is named: user, the alias is: myUser, both can be used

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration
public class MyConfigration {
    @Bean(name = "myUser")
    public User user() {
        return new User;
    }
}

The bean is named: user, the alias is: myUser / yourUser, all three can be used

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration
public class MyConfigration {
    @Bean(name = {"myUser", "yourUser"})
    public User user() {
        return new User;
    }
}

Bean initialization and destruction

public class MyBean {
    public void init() {
        System.out.println("MyBean初始化...");
    }
 
    public void destroy() {
        System.out.println("MyBean销毁...");
    }
 
    public String get() {
        return "MyBean使用...";
    }
}
@Bean(initMethod="init", destroyMethod="destroy")
public MyBean myBean() {
    return new MyBean();
}

Only @Bean can not be used @Component

@Bean
public OneService getService(status) {
    case (status)  {
        when 1:
                return new serviceImpl1();
        when 2:
                return new serviceImpl2();
        when 3:
                return new serviceImpl3();
    }
}

Reference: https://www.hangge.com/blog/cache/detail_2506.html

https://www.jianshu.com/p/2f904bebb9d0

https://www.cnblogs.com/feiyu127/p/7700090.html

https://www.jdon.com/50889

Guess you like

Origin www.cnblogs.com/danhuang/p/12692995.html