Spring @Configuration 和 @Bean 注解
Spring 注解 bean configuration
2023-09-11 14:22:20 时间
@Configuration 和 @Bean 注解
带有 @Configuration 的注解类表示这个类可以使用 Spring IoC 容器作为 bean 定义的来源。@Bean 注解告诉 Spring,一个带有 @Bean 的注解方法将返回一个对象,该对象应该被注册为在 Spring 应用程序上下文中的 bean。
例子如下:
HelloWorld.java
package com.how2java.w3cschool.baseonjava;
public class HelloWorld {
private String message;
public void getMessage() {
System.out.println("Your message is:" + message);
}
public void setMessage(String message) {
this.message = message;
}
}
HelloWorldConfig.java
package com.how2java.w3cschool.baseonjava;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/*
* 带有 @Configuration 的注解类表示这个类可以使用 Spring IoC 容器作为 bean 定义的来源。
* @Bean 注解告诉 Spring,一个带有 @Bean 的注解方法将返回一个对象,该对象应该被注册为在 Spring 应用程序上下文中的 bean。
*/
@Configuration
public class HelloWorldConfig {
// 带有 @Bean 注解的方法名称作为 bean 的 ID,它创建并返回实际的 bean。也就是此时的bean
// id为helloWorld,你的配置类可以声明多个 @Bean。
// 一旦定义了配置类,你就可以使用 AnnotationConfigApplicationContext 来加载并把他们提供给 Spring 容器
@Bean
public HelloWorld helloWorld() {
return new HelloWorld();
}
}
MainApp.java
package com.how2java.w3cschool.baseonjava;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(HelloWorldConfig.class);
HelloWorld helloWorld = ctx.getBean(HelloWorld.class);
helloWorld.setMessage("Hello World!");
helloWorld.getMessage();
}
}
如果在HelloWorldConfig.java中忘了@Bean的注解,将会遇到以下的错误
“No unique bean of type [com.how2java.w3cschool.baseonjava.HelloWorld] is defined: expected single bean but found 0: ”
例子源于:W3Cschool,在此作记录
相关文章
- [转] Spring注解@Component、@Repository、@Service、@Controller区别
- spring注解之@Import注解的三种使用方式(转载)
- Spring注解+Axis2开发WebService
- Spring AOP
- spring整合activemq发送MQ消息[Topic模式]实例
- MyBatis Spring SqlSessionFactoryBean 配置
- 普通spring jsp+mybatis项目修改为springboot + jsp +mybatis项目
- Spring常用注解
- spring aop使用,spring aop注解,Spring切面编程
- Spring的bean管理注解和配置文件混合使用
- Spring Boot 2 实战:使用 @Condition 注解来根据条件注入 Bean
- 如何在servlet的监听器中使用spring容器的bean
- spring框架漏洞整理(Spring Boot Actuator命令执行漏洞)
- spring框架漏洞整理(Spring WebFlow远程代码执行)
- spring 全局请求,根据请求类型返回json或html
- Spring_之注解事务 @Transactional
- spring注解@Transactional 和乐观锁,悲观锁并发生成有序编号问题
- 浅析Spring Bean的循环依赖问题、单例对象初始化三步、spring的三级缓存+提前曝光机制
- 深入理解Spring源码之剖析AOP(注解配置方式)
- Spring(存储Bean对象五大类注解,获取Bean对象三种注入方式)
- 从头认识Spring-2.3 注解装配-@autowired(4)-required(2)
- 【spring框架】通过注解配置事务(Transaction)
- 曹工说Spring Boot源码(23)-- ASM又立功了,Spring原来是这么递归获取注解的元注解的
- Spring Boot 使用 SpringDoc 库的 Swagger3.0