Spring @Bean注解详解
下文笔者将详细介绍@Bean注解的用法,如下所示:
@Bean注解的使用场景
@Bean注解常用于方法上, 方法体中的内容代表此Bean实际产生的逻辑 方法体的返回值为一个Bean 这个Bean会交给Spring进行管理 bean的命名通常采用 bean注解的方法名 注意事项: bean注解通常和Component或Configuration注解一起使用 -------------------------------------------------------------- @Bean注解类似于xml中如下的bean定义 <bean id="useService" class="com.test.service.UserServiceImpl"/>
@Bean注解的示例
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();
}
}
上述的Spring容器中,会生成一个名称为user的bean
例2:指定bean名称
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyConfigration {
@Bean(name = "javaUser")
public User user() {
return new User;
}
}
//采用以下命名方式后
//bean可使用 user,javaUser,maomaoUser中任意一个名称可都
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyConfigration {
@Bean(name = {"javaUser", "maomaoUser"})
public User user() {
return new User;
}
}
Bean初始化和销毁示例演示
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();
}
@Bean
public OneService getService(status) {
case (status) {
when 1:
return new serviceImpl1();
when 2:
return new serviceImpl2();
when 3:
return new serviceImpl3();
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


