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 ...
随机推荐
- 多线程实现的方式一继承Thread
实现方法一:继承Thread类 package thread; /** * @function 多线程继承Thread类 * @author hj */ public class Threads ex ...
- 【爬虫】大杀器——phantomJS+selenium
[爬虫]大杀器——phantomJS+selenium 视频地址 江湖上有一个传说,得倚天屠龙者可称霸武林.爬虫中也有两个大杀器,他们结合在一起时,无往不利,不管你静态网站还是动态网站,通吃. pha ...
- (三)IDEA使用,功能面板
IDEA 打开界面后周围有许多的功能面板 常用的界面 1.project:项目的目录结构: 2.Structure:结构界面:在这个界面里可以看到选择的类,接口 的结构,有哪些方法,字段,等: 3. ...
- 洛谷 P1140 相似基因 题解
每日一题 day23 打卡 Analysis dp[i][j]表示序列A中前i个与序列B中前j个匹配的相似度最大值 所以,dp方程很容易想到: 1.让a[i]与b[j]匹配 2.让a[i]与B序列中一 ...
- linux ps命令查看最消耗CPU、内存的进程
1.CPU占用最多的前10个进程: ps auxw|head -1;ps auxw|sort -rn -k3|head -10 2.内存消耗最多的前10个进程 ps auxw|head -1;ps a ...
- RookeyFrame Bug 线上创建的DLL被删除了 模块无法删除 临时解决
不知道什么情况 在线创建模块,DLL被删除了,但是模块的相关数据无法删除.可以按照下面的方法临时用一下. 产生这个的原因,好像是Config里面的NeedInit一直都是true,没有改为false, ...
- python3 结束子线程
最近公司内部网络经常出问题,奇慢无比,导致人脸检测程序在下载图片时经常卡住,为了不影响数据的核对, 决定在网络不佳图片下载超时后放弃下载,继续执行后续程序. 于是整理出解决思路如下: 1.在线程中完成 ...
- CODE FESTIVAL 2016 qual B题解
传送门 \(A\) 什么玩意儿-- const char t[]={"0CODEFESTIVAL2016"}; char s[25];int res; int main(){ sc ...
- 洛谷P3124被困在haybales
题目 按理来说是可以二分的,但是发现其实直接暴力然后注意细节就可以了. 先找到牛所在的起点,然后分别向右找和向左找. 第一次查找从\(r\)点冲到\(l\)点时,突破不了\(l\),从\(l\)点冲到 ...
- C语言实现多线程排序
#include <stdio.h> #include <pthread.h> #include <stdlib.h> #include <string.h& ...