spring的依赖注入

依赖

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.6.RELEASE</version>
</dependency>

xml方式

beanx.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="person" class="com.enjoy.cap1.Person">
        <property name="name" value="james"></property>
        <property name="age" value="19"></property>
    </bean>
</beans>

实体类

public class Person {
    private String name;
    private Integer age;
}

测试

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainTest1 { 
    public static void main(String args[]){
        //把beans.xml的类加载到容器
        ApplicationContext app = new ClassPathXmlApplicationContext("beans.xml");
        //从容器中获取bean
        Person person = (Person) app.getBean("person");
        
        System.out.println(person);
    }
}

注解方式

配置类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.enjoy.cap1.Person;

//配置类====配置文件
@Configuration
public class MainConfig {
    //给容器中注册一个bean, 类型为返回值的类型, 
    @Bean("XXX")
    public Person person01(){
        return new Person("james",20);
    }
}

测试

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.enjoy.cap1.config.MainConfig;

public class MainTest2 { 
    public static void main(String args[]){
        //把beans.xml的类加载到容器
        //ApplicationContext app = new ClassPathXmlApplicationContext("beans.xml");
        
        ApplicationContext app = new AnnotationConfigApplicationContext(MainConfig.class);
        
        //从容器中获取bean
        Person person = (Person) app.getBean("XXX");
        
        System.out.println(person);
        
        String[] namesForBean = app.getBeanNamesForType(Person.class);
        for(String name:namesForBean){
            System.out.println(name);
        }
        
        
    }
}

扫描方式

配置类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Controller;

import com.enjoy.cap1.Person;
import com.enjoy.cap2.controller.OrderController;

@Configuration
@ComponentScan(value="com.enjoy.cap2", includeFilters={        
        @Filter(type=FilterType.CUSTOM, classes={JamesTypeFilter.class})        
}, useDefaultFilters=false)


public class Cap2MainConfig {
    //给容器中注册一个bean, 类型为返回值的类型, 
    @Bean
    public Person person01(){
        return new Person("james",20);
    }
}    
        
@ComponentScan参数介绍:
    value:指扫描那个包下的注解。
    includeFilters 进行过滤,用这个参数的前提是必须把默认的过滤给关闭。useDefaultFilters=false
    @Filter(type=FilterType.CUSTOM, classes={JamesTypeFilter.class})    过滤的类型,自定义的过滤(这个类必须实现FilterType接口,在接口的实现方法上可以得到所有扫描的类,进行业务判断),类是 JamesTypeFilter类型,
    也可以用注解类型,类是Controller.class

自定义过滤类

import java.io.IOException;

import org.springframework.core.io.Resource;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.ClassMetadata;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.TypeFilter;

public class JamesTypeFilter implements TypeFilter{
    private ClassMetadata classMetadata;

    /*
     * MetadataReader:读取到当前正在扫描类的信息
     * MetadataReaderFactory:可以获取到其他任何类信息
     */
    
    @Override
    public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
            throws IOException {
        //获取当前类注解的信息
        AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
        //获取当前正在扫描的类信息
        classMetadata = metadataReader.getClassMetadata();
        //获取当前类资源(类的路径)
        Resource resource = metadataReader.getResource();
        
        String className = classMetadata.getClassName();
        System.out.println("----->"+className);
        if(className.contains("order")){//当类包含er字符, 则匹配成功,返回true
            return true;
        }
        return false;
    }

}

测试

public class Cap2Test {
    @Test
    public void test01(){
        AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext(Cap2MainConfig.class);
        String[] names = app.getBeanDefinitionNames(); 
        for(String name:names){
            System.out.println(name);
        }
    }
}

 @Conditional条件注册bean(实现Condition接口)

IOC容器注册bean时, 当操作系统为WINDOWS时,注册Lison实例; 当操作系统为LINUX时, 注册James实例,此时要用得@Conditional注解进行定制化条件选择注册bean

 

配置类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;

import com.enjoy.cap1.Person;
@Configuration
public class Cap5MainConfig {
    @Bean("person")
    public Person person(){
        System.out.println("给容器中添加person.......");
        return new Person("person",20);
    }
    
    @Conditional(WinCondition.class)
    @Bean("lison")
    public Person lison(){
        System.out.println("给容器中添加lison.......");
        return new Person("Lison",58);
    }
    @Conditional(LinCondition.class)
    @Bean("james")//bean在容器中的ID为james, IOC容器MAP,  map.put("id",value)
    public Person james(){
        System.out.println("给容器中添加james.......");
        return new Person("james",20);
    }
    
}

LinCondition 类

import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;

public class LinCondition implements Condition{

    
    
    /*
    *ConditionContext: 判断条件可以使用的上下文(环境)
    *AnnotatedTypeMetadata: 注解的信息
    *
    */
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        // TODO 是否为WINDOW系统
        //能获取到IOC容器正在使用的beanFactory
        ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
        //获取当前环境变量(包括我们操作系统是WIN还是LINUX??)
        Environment environment = context.getEnvironment();
        String os_name = environment.getProperty("os.name");
        if(os_name.contains("linux")){
            return true;
        }
        return false;
    }

}

WinCondition类

import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;

public class WinCondition implements Condition{

    
    
    /*
    *ConditionContext: 判断条件可以使用的上下文(环境)
    *AnnotatedTypeMetadata: 注解的信息
    *
    */
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        // TODO 是否为WINDOW系统
        //能获取到IOC容器正在使用的beanFactory
        ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
        //获取当前环境变量(包括我们操作系统是WIN还是LINUX??)
        Environment environment = context.getEnvironment();
        String os_name = environment.getProperty("os.name");
        if(os_name.contains("Windows")){
            return true;
        }
        return false;
    }

}

测试

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.enjoy.cap5.config.Cap5MainConfig;
public class Cap5Test {
    @Test
    public void test01(){
        AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext(Cap5MainConfig.class);
        System.out.println("IOC容器创建完成........");    
    }
}

 

posted @ 2019-04-28 22:42  发疯的man  阅读(445)  评论(0编辑  收藏  举报