通过@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的更多相关文章

  1. Spring总结 1.装配bean

    本随笔内容要点如下: 依赖注入 Spring装配bean的方式 条件化装配 一.依赖注入 我理解的依赖注入是这样的:所谓的依赖,就是对象所依赖的其他对象.Spring提供了一个bean容器,它负责创建 ...

  2. Spring通过注解装配Bean

    通过注解实现ServiceImpl业务 一.使用@Component装配Bean 1. 定义类:User 在类上面加@Component注解,在属性上面加@Value值 package com.wbg ...

  3. Spring 之自动化装配 bean 尝试

    [Spring之自动化装配bean尝试] 1.添加dependencies如下所示(不是每一个都用得到 <dependencies> <dependency> <grou ...

  4. spring中自动装配bean

    首先用@Component注解类: package soundsystem: import org.springframework.stereotype.Component; @Component p ...

  5. spring的自动装配Bean与自动检测Bean

    spring可以通过编写XML来配置Bean,也可以通过使用spring的注解来装配Bean. 1.自动装配与自动检测: 自动装配:让spring自动识别如何装配bean的依赖关系,减少对<pr ...

  6. Spring学习笔记—装配Bean

    在Spring中,对象无需自己负责查找或创建与其关联的其他对象.相反,容器负责把需要相互协作的对象引用赋予各个对象.创建应用对象之间协作关系的行为通常称为装配(wiring),这也是依赖注入的本质. ...

  7. spring实战三装配bean之Bean的作用域以及初始化和销毁Bean

    1.Bean的作用域 所有的spring bean默认都是单例.当容器分配一个Bean时,不论是通过装配还是调用容器的getBean()方法,它总是返回Bean的同一个实例.有时候需要每次请求时都获得 ...

  8. spring实战一:装配bean之注入Bean属性

    内容参考自spring in action一书. 创建应用对象之间协作关系的行为通常称为装配,这也是依赖注入的本质. 1. 创建spring配置 spring是一个基于容器的框架.如果没有配置spri ...

  9. Spring框架---IOC装配Bean

    IOC装配Bean (1)Spring框架Bean实例化的方式提供了三种方式实例化Bean 构造方法实例化(默认无参数,用的最多) 静态工厂实例化 实例工厂实例化 下面先写这三种方法的applicat ...

  10. 【Spring 核心】装配bean(三)XML配置

    项目包结构: src/main/java com.bonc.pojo--|-CompactDisc.java (接口) |-SgtPeppers.java     (实现类 实现 CompactDis ...

随机推荐

  1. docker 进程 转载:

    今天我们会分析Docker中进程管理的一些细节,并介绍一些常见问题的解决方法和注意事项. 容器的PID namespace(名空间) 在Docker中,进程管理的基础就是Linux内核中的PID名空间 ...

  2. pycharm 代码跟进以跳回/返回

    方法1 View-->Toolbar-->左上方的左右箭头,可以跳转光标位置,左箭头可以放回 方法2 设置快捷键 setting-->keymap-->Main menu--& ...

  3. 最小费用流模板(zkw与spfa)

    "zkw" 费用流算法在哪些图上慢(摘自https://www.cnblogs.com/ECJTUACM-873284962/p/7744943.html) 实践中, 上面的这个算 ...

  4. IDEA设置提示生成序列化ID

    背景: 实现Serializable接口的类,没有提示生成序列化ID 解决问题: 1.FIle->Settings->Editor->inspections 2.点击java-> ...

  5. 洛谷 P5640 【CSGRound2】逐梦者的初心 题解

    每日一题 day33 打卡 Analysis 这道题太难♂了,居然才是蓝的. 每个位子和每种字符都是独立的,对每种字符都记录一下位子. 用f[i]=0 or 1 表示长度为ii的后缀可不可以,0表示可 ...

  6. [转载]JSON WEB TOKEN,简单谈谈TOKEN的使用及在C#中的实现

    https://www.cnblogs.com/chenwolong/p/Token.html

  7. CF463D Gargari and Permutations dp

    给定 $n<=10$ 个 $1$~$n$ 的排列,求这些排列的 $LCS$. 考虑两个排列怎么做:以第一个序列为基准,将第二个序列的元素按照该元素在第一个序列中出现位置重新编号. 然后,求一个 ...

  8. Springboot如何优雅的解决ajax+自定义headers的跨域请求[转]

    1.什么是跨域 由于浏览器同源策略(同源策略,它是由Netscape提出的一个著名的安全策略.现在所有支持JavaScript 的浏览器都会使用这个策略.所谓同源是指,域名,协议,端口相同.),凡是发 ...

  9. phpize是干嘛的

    安装php(fastcgi模式)的时候,常常有这样一句命令:/usr/local/webserver/php/bin/phpize一.phpize是干嘛的?phpize是什么东西呢?php官方的说明: ...

  10. C++标准库分析总结(九)——<HashFunction、Tuple>

    一.HashFunction 当我们在使用hash table以及由它做底层的数据结构时,我们必不可少要讨论hash function,所谓的哈希函数就是产生一个数,这个数越乱越好,以至于达到避免碰撞 ...