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();
spring 使用@Bean装配Bean的更多相关文章
- Spring总结 1.装配bean
本随笔内容要点如下: 依赖注入 Spring装配bean的方式 条件化装配 一.依赖注入 我理解的依赖注入是这样的:所谓的依赖,就是对象所依赖的其他对象.Spring提供了一个bean容器,它负责创建 ...
- Spring通过注解装配Bean
通过注解实现ServiceImpl业务 一.使用@Component装配Bean 1. 定义类:User 在类上面加@Component注解,在属性上面加@Value值 package com.wbg ...
- Spring 之自动化装配 bean 尝试
[Spring之自动化装配bean尝试] 1.添加dependencies如下所示(不是每一个都用得到 <dependencies> <dependency> <grou ...
- spring中自动装配bean
首先用@Component注解类: package soundsystem: import org.springframework.stereotype.Component; @Component p ...
- spring的自动装配Bean与自动检测Bean
spring可以通过编写XML来配置Bean,也可以通过使用spring的注解来装配Bean. 1.自动装配与自动检测: 自动装配:让spring自动识别如何装配bean的依赖关系,减少对<pr ...
- Spring学习笔记—装配Bean
在Spring中,对象无需自己负责查找或创建与其关联的其他对象.相反,容器负责把需要相互协作的对象引用赋予各个对象.创建应用对象之间协作关系的行为通常称为装配(wiring),这也是依赖注入的本质. ...
- spring实战三装配bean之Bean的作用域以及初始化和销毁Bean
1.Bean的作用域 所有的spring bean默认都是单例.当容器分配一个Bean时,不论是通过装配还是调用容器的getBean()方法,它总是返回Bean的同一个实例.有时候需要每次请求时都获得 ...
- spring实战一:装配bean之注入Bean属性
内容参考自spring in action一书. 创建应用对象之间协作关系的行为通常称为装配,这也是依赖注入的本质. 1. 创建spring配置 spring是一个基于容器的框架.如果没有配置spri ...
- Spring框架---IOC装配Bean
IOC装配Bean (1)Spring框架Bean实例化的方式提供了三种方式实例化Bean 构造方法实例化(默认无参数,用的最多) 静态工厂实例化 实例工厂实例化 下面先写这三种方法的applicat ...
- 【Spring 核心】装配bean(三)XML配置
项目包结构: src/main/java com.bonc.pojo--|-CompactDisc.java (接口) |-SgtPeppers.java (实现类 实现 CompactDis ...
随机推荐
- 简述 OSI 七层协议?
OSI七层协议是一个用于计算机或通信系统间互联的标准体系. 物理层功能:主要是基于电器特性发送高低电压(电信号),高电压对应数字1,低电压对应数字0. 数据链路层的功能:定义了电信号的分组方式按照以太 ...
- Kubernetes 学习3 kubeadm初始化k8s集群
一.k8s集群 1.k8s整体架构图 2.k8s网络架构图 二.基于kubeadm安装k8s步骤 1.master,nodes:安装kubelet,kubeadm,docker 2.master: k ...
- 【HTML】解析原理
标准的web前端工程师需要知道 ◎浏览器(或者相应播放器)的渲染/重绘原理 这我得加把劲了.我还真的说的不是很清楚,我就G下,结果不是很多,找到了有一个,就记下来了... 以下部分来自handawei ...
- mysql 5.7.21, for Linux (i686) 权限配置
配置权限参数: GRANT语法: GRANT 权限 ON 数据库.* TO 用户名@'登录主机' IDENTIFIED BY '密码' 权限: ALL,ALTER,CREATE,DROP,SELECT ...
- AtCoder Grand Contest 010题解
传送门 \(A\) 判一下奇数的个数就行了 const int N=1e5+5; int a[N],n,res; int main(){ scanf("%d",&n); f ...
- Luogu4294 【WC2008】游览计划
斯坦纳树(我也不知道为什么叫这个名字)是一种状压dp的套路,求在无向带花连通图中,选取边使一些特殊点连通起来的最小花费. 具体到这题就是这样的,设\(f_{u,S}\)表示当前根是\(u\),与它连通 ...
- Chrome教程(二)使用ChromeDevTools命令菜单运行命令
1.模拟移动设备 点击 Toggle Device Toolbar可以打开用于模拟移动设备视口的界面. 2.限制网络流量和 CPU 占用率 要限制网络流量和 CPU 占用率,请从 Throttle 列 ...
- 《挑战30天C++入门极限》C++运算符重载函数基础及其值返回状态
C++运算符重载函数基础及其值返回状态 运算符重载是C++的重要组成部分,它可以让程序更加的简单易懂,简单的运算符使用可以使复杂函数的理解更直观. 对于普通对象来说我们很自然的会频繁使用算数运 ...
- windows下powershell的包管理工具
scoop github 开源地址:https://github.com/lukesampson/scoop 安装命令->powershell管理员模式下输入 Invoke-Expression ...
- Pytest权威教程24-Pytest导入机制及系统路径
目录 Pytest导入机制和sys.path/PYTHONPATH 包中的测试脚本及conftest.py文件 独立测试模块及conftest.py文件 调用通过python -m pytest调用p ...