zoukankan      html  css  js  c++  java
  • 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();
  • 相关阅读:
    SQL Functions
    wse 3.0
    mvc2 在 .net 4 下的ValidateInput(false) 无效
    FF3.0 不可以post空
    也谈.NET MVC 2 + ExtJS的部署问题
    ExtJs懒人笔记(2) ExtJs页面布局
    关于算法—— 一维字符串数组之间组合问题的C#实现
    (转)在ASP.NET 中实现单点登录(利用Cache, 将用户信息保存在服务器缓存中)
    XML中配置正则表达式的写法
    .NET MVC 下实现消息推送
  • 原文地址:https://www.cnblogs.com/ooo0/p/10975999.html
Copyright © 2011-2022 走看看