Spring @Bean 注释教程展示了如何使用@Bean 注释在 Java 配置类中声明 bean。
Spring 是用于创建企业应用的流行 Java 应用框架。
Spring @Bean
@Bean注释指示带注释的方法产生要由 Spring 容器管理的 bean。 它是<bean/> XML 标签的直接模拟。 @Bean支持<bean/>提供的大多数属性,例如:init-method,destroy-method,autowiring,lazy-init,dependency-check,depends-on,scope。
Spring @Bean示例
该应用生成带有@Bean注解的 Spring 托管 bean。 它还为 bean 提供了一些别名。
pom.xmlsrc├───main│ ├───java│ │ └───com│ │ └───zetcode│ │ │ Application.java│ │ ├───bean│ │ │ HelloMessage.java│ │ └───config│ │ AppConfig.java│ └───resources│ logback.xml│ messages.properties└───test └───java
这是项目结构。
pom.xml
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.zetcode</groupId> <artifactId>beanannotation</artifactId> <version>1.0-SNAPSHOT</version> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>11</maven.compiler.source> <maven.compiler.target>11</maven.compiler.target> <spring-version>5.1.3.RELEASE</spring-version> </properties> <dependencies> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>{spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>{spring-version}</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.6.0</version> <configuration> <mainClass>com.zetcode.Application</mainClass> </configuration> </plugin> </plugins> </build></project>在pom.xml文件中,我们具有基本的 Spring 依赖项spring-core,spring-context和日志记录logback-classic依赖项。
exec-maven-plugin用于在命令行上从 Maven 执行 Spring 应用。
resources/logback.xml
<?xml version="1.0" encoding="UTF-8"?><configuration> <logger name="org.springframework" level="ERROR"/> <logger name="com.zetcode" level="INFO"/> <appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <Pattern>%d{HH:mm:ss.SSS} %blue(%-5level) %magenta(%logger{36}) - %msg %n </Pattern> </encoder> </appender> <root> <level value="INFO" /> <appender-ref ref="consoleAppender" /> </root></configuration>logback.xml是 Logback 日志库的配置文件。
resources/message.properties
motd="Hello there!"
message.properties包含 day 属性的消息,由我们的HelloMessage bean 使用。 这为应用提供了更大的灵活性,并避免了将消息硬编码为 Java 代码。
com/zetcode/bean/HelloMessage.java
package com.zetcode.bean;public class HelloMessage { private String message; public HelloMessage(String message) { this.message = message; } public String getMessage() { return message; }}HelloMessage bean 是使用@Bean注释方法创建的。
com/zetcode/config/AppCofig.java
package com.zetcode.config;import com.zetcode.bean.HelloMessage;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.PropertySource;@Configuration@PropertySource(value="messages.properties")public class AppConfig { @Value("${motd}") private String message; @Bean(name={"myMessage", "motd"}) public HelloMessage helloMessageProducer() { var helloMessage = new HelloMessage(message); return helloMessage; }}我们在AppConfig中定义了HelloMessage生产者。
@Configuration@PropertySource(value="messages.properties")public class AppConfig {使用@Configuration,我们声明AppConfig是配置类。 @PropertySource注解允许我们通过@Value轻松使用messages.properties文件中的属性。
@Value("${motd}")private String message;我们将motd属性注入到message属性中。
@Bean(name={"myMessage", "motd"})public HelloMessage helloMessageProducer() { var helloMessage = new HelloMessage(message); return helloMessage;}helloMessageProducer()产生一个新的HelloMessage bean。 它从外部属性获取消息。 @Bean注释使HelloMessage bean 由 Spring 生产和管理。 另外,我们给 Bean 两个别名。
com/zetcode/Application.java
package com.zetcode;import com.zetcode.bean.HelloMessage;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.context.annotation.AnnotationConfigApplicationContext;import org.springframework.context.annotation.ComponentScan;@ComponentScan(basePackages = "com.zetcode")public class Application { private static final Logger logger = LoggerFactory.getLogger(Application.class); public static void main(String[] args) { var ctx = new AnnotationConfigApplicationContext(Application.class); var msgBean1 = ctx.getBean(HelloMessage.class); logger.info("{}", msgBean1.getMessage()); var msgBean2 = (HelloMessage) ctx.getBean("myMessage"); logger.info("{}", msgBean2.getMessage()); var msgBean3 = (HelloMessage) ctx.getBean("motd"); logger.info("{}", msgBean3.getMessage()); ctx.close(); }}该应用带有@ComponentScan注释。 basePackages选项告诉 Spring 在com/zetcode包及其子包中查找组件。
var ctx = new AnnotationConfigApplicationContext(Application.class);
AnnotationConfigApplicationContext是 Spring 独立应用上下文。 它接受带注释的Application作为输入; 因此启用了扫描。
var msgBean1 = ctx.getBean(HelloMessage.class);logger.info("{}", msgBean1.getMessage());我们通过其类型来获取 bean。
var msgBean2 = (HelloMessage) ctx.getBean("myMessage");logger.info("{}", msgBean2.getMessage());var msgBean3 = (HelloMessage) ctx.getBean("motd");logger.info("{}", msgBean3.getMessage());在这里,我们通过别名获得相同的 bean。
$ mvn -q exec:java14:39:29.324 INFO com.zetcode.Application - "Hello there!" 14:39:29.324 INFO com.zetcode.Application - "Hello there!" 14:39:29.324 INFO com.zetcode.Application - "Hello there!"
我们运行该应用。
在本教程中,我们使用了@Bean注释来生成托管的 Spring bean。
