Spring之注解开发管理第三方bean

1.第三方bean管理

(1)首先定义一个第三方类,然后定义一个方法,在方法上加@Bean注解,方法的返回值就是要管理的bean

package config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;

public class JdbcConfig {
    @Bean("dataSource")//@Bean:按类型自动装配;@Bean("dataSource"):按名称自动装配
    //方法名建议起成要管理的bean的id名称
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/spring_demo?useUnicode=true&characterEncoding=utf-8");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        return dataSource;
    }
}

(2)在Spring的配置类上加@Import注解导入第三方bean

ackage config;

import org.springframework.context.annotation.*;



@Configuration
@Import(JdbcConfig.class)
public class SpringConfig {
}

注:有多个配置类,需以数组的形式导入.例:@Import({JdbcConfig.class,XXX.class,…})

2.第三方bean依赖注入

(1)简单数据类型依赖注入
在第三方类中定义属性,使用@Value注解实现依赖注入

package config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;

public class JdbcConfig {
    @Value("com.mysql.jdbc.Driver")
    private String driverClassName;
    @Value("jdbc:mysql://localhost:3306/spring_demo?useUnicode=true&characterEncoding=utf-8")
    private String url;
    @Value("root")
    private String username;
    @Value("123456")
    private String password;
    @Bean("dataSource")
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }
}

(2)引用数据类型依赖注入
在方法中定义引用数据类型的形参(注:形参的引用数据类型需要在IoC中有对应的bean)

package config;

import com.alibaba.druid.pool.DruidDataSource;
import domain.Animal;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;

public class JdbcConfig {
    @Value("com.mysql.jdbc.Driver")
    private String driverClassName;
    @Value("jdbc:mysql://localhost:3306/spring_demo?useUnicode=true&characterEncoding=utf-8")
    private String url;
    @Value("root")
    private String username;
    @Value("123456")
    private String password;
    @Bean("dataSource")
    public DataSource dataSource(Animal animal) {
        System.out.println(animal);
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }
}

你可能感兴趣的:(Spring,spring,java,后端)