博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
spring 使用@Bean装配Bean
阅读量:6918 次
发布时间:2019-06-27

本文共 3478 字,大约阅读时间需要 11 分钟。

  通过@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;@Componentpublic 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;@Componentpublic 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:

 

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();

 

转载于:https://www.cnblogs.com/ooo0/p/10975999.html

你可能感兴趣的文章
上不了网,我的解决过程
查看>>
不连续子网掩码的魅力
查看>>
查看Nginx,Apache,lighttpd,Mysql,Php的编译参数
查看>>
在RHEL5下使用bind构建分离解析的域名服务器
查看>>
修复点击网卡本地连接属性无反应netshell注册失败80020009问题
查看>>
ExtJS4.2学习(22)登录界面
查看>>
MySQL下的安全问题--.mysql_history你注意到了吗?
查看>>
Oracle 11gR2 安装RAC错误之--HOSTS文件错误
查看>>
linux下必看的60个命令
查看>>
Iptables 对服务器的简单防护策略
查看>>
HowTo 激活非常规方式安装的正版OEM Vista
查看>>
洛谷P1387 最大正方形
查看>>
RecyclerView学习(四)----ItemDecoration实现的城市导航列表(下)
查看>>
FTP文件管理
查看>>
使用Configuration Manager部署操作系统(2)
查看>>
AC自动机 - 关于Fail指针
查看>>
word文档打印之后出打印报告
查看>>
SQL Server 变量名称的Collcation跟Instance还是跟当前DB?
查看>>
美商务部盛赞McAfee SiteAdvisor安全上网工具
查看>>
openstack实例热迁移
查看>>