spring 使用@Bean裝配Bean

  經過@Component裝配Bean,可是@Component只能註解在類上,不能註解到方法上。對於Java而言,大部分的開發都須要引入第三方的包(jar文件),並且每每並無這些包的源碼,這時候將沒法爲這些包的類加入@Component註解,讓它們變爲開發環境的Bean。你可使用新類擴展(extends)其包內的類,而後在新類上使用@Component,可是這樣又顯得不三不四。這個時候Spring給予一個註解@Bean,它能夠註解到方法之上,而且將方法返回的對象做爲Spring的Bean,存放在IoC容器中。好比咱們須要使用DBCP數據源,這個時候要引入關於它的包,而後能夠經過代碼清單來裝配數據源的Bean。
  代碼清單:經過註解@Bean裝配數據源Beanjava

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中。mysql

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:spring

<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();
相關文章
相關標籤/搜索