spring 使用@Bean装配Bean
通过@Component装配Bean,但是@Component只能注解在类上,不能注解到方法上。对于Java而言,大部分的开发都需要引入第三方的包(jar文件),而且往往并没有这些包的源码,这时候将无法为这些包的类加入@Component注解,让它们变为开发环境的Bean。你可以使用新类扩展(extends)其包内的类,然后在新类上使用@Component,但是这样又显得不伦不类。这个时候Spring给予一个注解@Bean,它可以注解到方法之上,并且将方法返回的对象作为Spring的Bean,存放在IoC容器中。比如我们需要使用DBCP数据源,这个时候要引入关于它的包,然后可以通过代码清单来装配数据源的Bean。
代码清单:通过注解@Bean装配数据源Bean
import org.apache.commons.dbcp.BasicDataSourceFactory; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; import javax.sql.DataSource; import java.util.Properties; @Component public class AnnotationBean { @Bean(name = "dataSource2") public DataSource getDataSource() { Properties props = new Properties(); props.setProperty("driver", "com.mysql.cj.jdbc.Driver"); props.setProperty("url", "jdbc:mysql://localhost:3306/springmvc?useSSL=false&serverTimezone=Hongkong&characterEncoding=utf-8&autoReconnect=true"); props.setProperty("username", "root"); props.setProperty("password", "123456"); DataSource dataSource = null; try { dataSource = (DataSource) BasicDataSourceFactory.createDataSource(props); System.out.println("getDataSource init"); } catch (Exception e) { e.printStackTrace(); } return dataSource; } }
这样就能够装配一个Bean,当Spring IoC容器扫描它的时候,就会为其生成对应的Bean。这里还配置了@Bean的name选项为dataSource2,这就意味着Spring生成该Bean的时候就会使用dataSource2作为其BeanName。和其他Bean一样,它也可以通过@Autowired或者@Qualifier等注解注入别的Bean中。
import com.ssm.chapter10.annotation.pojo.Role; import com.ssm.chapter10.annotation.service.RoleDataSourceService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @Component public class RoleDataSourceServiceImpl implements RoleDataSourceService { @Autowired @Qualifier("dataSource2") DataSource dataSource = null; // @Override public Role getRole(Long id) { Connection conn = null; ResultSet rs = null; PreparedStatement ps = null; Role role = null; try { conn = dataSource.getConnection(); ps = conn.prepareStatement("select id, role_name, note from t_role where id = ?"); ps.setLong(1, id); rs = ps.executeQuery(); while (rs.next()) { role = new Role(); role.setId(rs.getLong("id")); role.setRoleName(rs.getString("role_name")); role.setNote(rs.getString("note")); } } catch (SQLException e) { e.printStackTrace(); } finally { /**********close database resources************/ try { rs.close(); ps.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } } return role; } }
spring-dataSource.xml:
<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"> <context:component-scan base-package="com.ssm.chapter10.annotation"/> </beans>
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("ssm/chapter10/spring-dataSource.xml"); RoleDataSourceServiceImpl roleDataSourceServiceImpl = context.getBean(RoleDataSourceServiceImpl.class); Role role = roleDataSourceServiceImpl.getRole(1L); System.out.println(role.toString()); context.close();
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律