码迷,mamicode.com
首页 > 编程语言 > 详细

spring-注解 (1)

时间:2018-10-25 12:02:54      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:assert   返回   value   include   组件   注册   factory   play   contain   

    spring-注解 (1) -- include/exclude

技术分享图片

技术分享图片
package com.zwj.bean;

import org.springframework.stereotype.Component;

@Component
public class Car {
    
    public Car(){
        System.out.println("car constructor...");
    }
    
    public void init(){
        System.out.println("car ... init...");
    }
    
    public void detory(){
        System.out.println("car ... detory...");
    }

}
Car
技术分享图片
package com.zwj.bean;

import org.springframework.beans.factory.annotation.Value;

public class Person {
    
    //使用@Value赋值;
    //1、基本数值
    //2、可以写SpEL; #{}
    //3、可以写${};取出配置文件【properties】中的值(在运行环境变量里面的值)
    
    @Value("张三")
    private String name;
    @Value("#{20-2}")
    private Integer age;
    
    @Value("${person.nickName}")
    private String nickName;
    
    
    
    public String getNickName() {
        return nickName;
    }
    public void setNickName(String nickName) {
        this.nickName = nickName;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    
    public Person(String name, Integer age) {
        super();
        this.name = name;
        this.age = age;
    }
    public Person() {
        super();
        // TODO Auto-generated constructor stub
    }
    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + ", nickName=" + nickName + "]";
    }

    
    
    
    
    
    

}
Persion
技术分享图片
package com.zwj.config;

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

import com.zwj.bean.Person;
import com.zwj.service.BookService;

import org.springframework.context.annotation.ComponentScan.Filter;


import org.springframework.context.annotation.ComponentScans;

//配置类==配置文件


/*@ComponentScans(
        value = {
                @ComponentScan(value="com.atguigu",includeFilters = {
                        @Filter(type=FilterType.ANNOTATION,classes={Controller.class}),
                        @Filter(type=FilterType.ASSIGNABLE_TYPE,classes={BookService.class}),
                        @Filter(type=FilterType.CUSTOM,classes={MyTypeFilter.class})
                },useDefaultFilters = false)    
        }
        )*/
//@ComponentScan  value:指定要扫描的包
//excludeFilters = Filter[] :指定扫描的时候按照什么规则排除那些组件
//includeFilters = Filter[] :指定扫描的时候只需要包含哪些组件
//FilterType.ANNOTATION:按照注解
//FilterType.ASSIGNABLE_TYPE:按照给定的类型;
//FilterType.ASPECTJ:使用ASPECTJ表达式
//FilterType.REGEX:使用正则指定
//FilterType.CUSTOM:使用自定义规则
@ComponentScans(
        value = {
                @ComponentScan(value="com.zwj",excludeFilters= {
                    //指定某一个注解@controller/@repository/@compnement/@service ,不加入到IOC容器
                    @Filter(type=FilterType.ANNOTATION,classes= {Controller.class}),
                    // 指定具体某一个类,不注入到IOC容器里
                    @Filter(type=FilterType.ASSIGNABLE_TYPE,classes={BookService.class})
                })
        }
        )
@Configuration  //告诉Spring这是一个配置类
public class MainConfigExclude {
    
    //给容器中注册一个Bean;类型为返回值的类型,id默认是用方法名作为id
    @Bean("person")
    public Person person01(){
        return new Person("lisi", 20);
    }

}
MainConfigExclude
技术分享图片
package com.zwj.config;

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

import com.zwj.bean.Person;
import com.zwj.service.BookService;

import org.springframework.context.annotation.ComponentScan.Filter;


import org.springframework.context.annotation.ComponentScans;

@ComponentScans(
        value = {
                @ComponentScan(value="com.zwj",includeFilters = {
                        @Filter(type=FilterType.ANNOTATION,classes={Controller.class}),
                        @Filter(type=FilterType.ASSIGNABLE_TYPE,classes={BookService.class}),
                        // 自定义过滤规则
                        @Filter(type=FilterType.CUSTOM,classes={MyTypeFilter.class})
                  //关闭默认,默认是加载所有的@controller/service/repository/component
                },useDefaultFilters = false)    
        }
        )
@Configuration  //告诉Spring这是一个配置类
public class MainConfigInclude {
    
    //给容器中注册一个Bean;类型为返回值的类型,id默认是用方法名作为id
    @Bean("person")
    public Person person01(){
        return new Person("lisi", 20);
    }

}
MainConfigInclude
技术分享图片
package com.zwj.config;

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 MyTypeFilter implements TypeFilter {

    /**
     * metadataReader:读取到的当前正在扫描的类的信息
     * metadataReaderFactory:可以获取到其他任何类信息的
     */
    public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
            throws IOException {
        // TODO Auto-generated method stub
        //获取当前类注解的信息
        AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
        //获取当前正在扫描的类的类信息
        ClassMetadata classMetadata = metadataReader.getClassMetadata();
        //获取当前类资源(类的路径)
        Resource resource = metadataReader.getResource();
        
        String className = classMetadata.getClassName();
        System.out.println("--->"+className);
        if(className.contains("er")){
            return true;
        }
        return false;
    }

}
MyTypeFilter
技术分享图片
package com.zwj.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.zwj.service.BookService;


@Controller
public class BookController {
    
    @Autowired
    private BookService bookService;

}
BookController
技术分享图片
package com.zwj.dao;

import org.springframework.stereotype.Repository;

//名字默认是类名首字母小写
@Repository
public class BookDao {
    
    private String lable = "1";

    public String getLable() {
        return lable;
    }

    public void setLable(String lable) {
        this.lable = lable;
    }

    @Override
    public String toString() {
        return "BookDao [lable=" + lable + "]";
    }
    
    
    
    

}
BookDao
技术分享图片
package com.zwj.service;


import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.zwj.dao.BookDao;



@Service
public class BookService {
    
    //@Qualifier("bookDao")
    //@Autowired(required=false)
    //@Resource(name="bookDao2")
    /*@Inject*/
    @Autowired(required=false)
    private BookDao bookDao;
    
    public void print(){
        System.out.println(bookDao);
    }

    @Override
    public String toString() {
        return "BookService [bookDao=" + bookDao + "]";
    }
    
    
    
    

}
BookService
技术分享图片
package com.zwj.test;

import static org.junit.Assert.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.sun.xml.internal.ws.addressing.v200408.MemberSubmissionAddressingConstants;
import com.zwj.bean.Person;
import com.zwj.config.MainConfigExclude;
import com.zwj.config.MainConfigInclude;


public class IocTest {

    @Test
    public void testExclude() {
        AnnotationConfigApplicationContext acac = new     AnnotationConfigApplicationContext(MainConfigExclude.class);
           // 取出所有注入到IOC容器的key 的名字
           String[]   names = acac.getBeanDefinitionNames();
           for (String string : names) {
            System.out.println(string);
           }
           // 取出IOC容器中的对象
           Person person = acac.getBean(Person.class);
           System.out.println(person);
      
    }
    
/*
mainConfigExclude
car
mainConfigInclude
bookDao
person
myTypeFilter
bookController
bookService
Person [name=张三, age=18, nickName=${person.nickName}]
 */
    @Test
    public void testInclude() {
        AnnotationConfigApplicationContext acac = new     AnnotationConfigApplicationContext(MainConfigInclude.class);
           // 取出所有注入到IOC容器的key 的名字
           String[]   names = acac.getBeanDefinitionNames();
           for (String string : names) {
            System.out.println(string);
           }
           // 取出IOC容器中的对象
           Person person = acac.getBean(Person.class);
           System.out.println(person);
      
    }
/*
mainConfigInclude
person
myTypeFilter
bookController
bookService
Person [name=张三, age=18, nickName=${person.nickName}]
*/
}
IocTest
技术分享图片
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.zwj</groupId>
  <artifactId>spring-annotation-config</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  <dependencies>
       <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.12.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
   
  </dependencies>
  
  
</project>
pom.xml

 

github 地址 :https://github.com/typecone/spring-annotation.git

 

spring-注解 (1)

标签:assert   返回   value   include   组件   注册   factory   play   contain   

原文地址:https://www.cnblogs.com/ou-pc/p/9848711.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!