1.基于java的容器配置

1.1.基本概念: @Bean 和 @Configuration

1.1.1 绑定Java与XML配置

  1. import com.alibaba.druid.pool.DruidDataSource;
  2. import com.xixi.MyImportBeanDefinitionRegistrar;
  3. import com.xixi.MyImportSelcetor;
  4. import com.xixi.User;
  5. import org.springframework.beans.factory.annotation.Value;
  6. import org.springframework.context.annotation.*;
  7. //用户标记一个Spring配置类,之前是配置的xml文件
  8. @Configuration
  9. @ComponentScan(basePackages = "com.xixi")
  10. @PropertySource("classpath:db.properties")
  11. public class IocJavaConfig {
  12. @Value("${mysql.username}")
  13. public String username;
  14. @Value("${mysql.password}")
  15. public String password;
  16. @Value("${mysql.url}")
  17. public String url;
  18. @Value("${mysql.driverClass}")
  19. public String driverClass;
  20. @Bean(value = "user2")
  21. public User getUser(){
  22. return new User();
  23. }
  24. //第三方类引入
  25. @Bean
  26. public DruidDataSource dataSource(User user){
  27. System.out.println("user:"+user);
  28. DruidDataSource druidDataSource = new DruidDataSource();
  29. druidDataSource.setName(username);
  30. druidDataSource.setPassword(password);
  31. druidDataSource.setUrl(url);
  32. druidDataSource.setDriverClassName(driverClass);
  33. System.out.println(user4());
  34. return druidDataSource;
  35. }
  36. @Bean
  37. public User user4(){
  38. return new User();
  39. }
  40. }

1.2 如何测试

使用AnnotationConfigApplicationContext初始化Spring容器

         private AnnotationConfigApplicationContext context;

    @Before
    public void init() {
        context = new AnnotationConfigApplicationContext(IocJavaConfig.class);
    }


    @Test
    public void test1() {
        System.out.println(context.getBean("user"));
        System.out.println(context.getBean("user2"));
    }

2.@Bean的注解

2.1 声明一个bean

image.png

2.2 bean的依赖

image.png

2.3 指定bean的作用域

@Configuration
public class MyConfiguration {

    @Bean
    @Scope("prototype")
    public Encryptor encryptor() {
        // ...
    }
}

2.4 自定义Bean的名字

//默认情况下,配置类使用@Bean方法的名称作为结果bean的名称。 
//但是,可以使用name属性覆盖此功能,如以下示例所示:
@Configuration
public class AppConfig {

    @Bean(name = "myThing")
    //多个别名:@Bean(name = { "dataSource", "subsystemA-dataSource", "subsystemB-dataSource" })
    public Thing thing() {
        return new Thing();
    }
}

2.5 @Configuration 注解

//当Bean彼此有依赖关系时,表示依赖关系就像调用另一个bean方法一样简单.如下例所示:
@Configuration
public class AppConfig {

    @Bean
    public BeanOne beanOne() {
        return new BeanOne(beanTwo());
    }

    @Bean
    public BeanTwo beanTwo() {
        return new BeanTwo();
    }
}

3.@Import

import com.alibaba.druid.pool.DruidDataSource;
import com.xixi.MyImportBeanDefinitionRegistrar;
import com.xixi.MyImportSelcetor;
import com.xixi.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;

//用户标记一个Spring配置类,之前是配置的xml文件
@Configuration
@ComponentScan(basePackages = "com.xixi")
@PropertySource("classpath:db.properties")
//@Import
//1.导入其他的配置类 @Import(value = {SecondJavaConfig.class})
//2.导入类注册为一个Bean @Import(value = {User.class})
//3.导入ImportSelector实现类,可以注册多个bean
//4.导入ImportBeanDefinitionRegistrar实现类,可以注册多个BeanDefinition
//@Import(value = {SecondJavaConfig.class, MyImportSelcetor.class})
//@Import(MyImportSelcetor.class)
@Import(MyImportBeanDefinitionRegistrar.class)
public class IocJavaConfig {

    @Value("${mysql.username}")
    public String username;

    @Value("${mysql.password}")
    public String password;


    @Value("${mysql.url}")
    public String url;

    @Value("${mysql.driverClass}")
    public String driverClass;

    @Bean(value = "user2")
    public User getUser(){
        return new User();
    }


    //第三方类引入
    @Bean
    public DruidDataSource dataSource(User user){
        System.out.println("user:"+user);
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setName(username);
        druidDataSource.setPassword(password);
        druidDataSource.setUrl(url);
        druidDataSource.setDriverClassName(driverClass);
        System.out.println(user4());
        return druidDataSource;
    }
    @Bean
    public User user4(){
        return new User();
    }

}

3.1 ImportSelector

package com.xixi;

import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.stereotype.Component;

@Component
public class MyImportSelcetor implements ImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        //可以以字符串的形式注册多个bean
        //字符串必须是全类型限定名 getBean()不能使用名称获取,只能以Class形式获取
        return new String[]{"com.xixi.Person","com.xixi.Wife"};
    }
}

3.2 ImportBeanDefinitionRegistrar

package com.xixi;

import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;


public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {

        GenericBeanDefinition genericBeanDefinition = new GenericBeanDefinition();

        genericBeanDefinition.setBeanClass(Person.class);

        registry.registerBeanDefinition("person",genericBeanDefinition);

    }
}

将一个类注入到ioc中:
1.xml:
2.@Component (@Controller,@Service,@Repository)
3.@Bean
@Import