spring-注解

Posted 周无极

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring-注解 相关的知识,希望对你有一定的参考价值。

    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-注解 的主要内容,如果未能解决你的问题,请参考以下文章

使用Java代码和注解完成Spring配置

Spring Boot实战笔记-- Spring高级话题(组合注解与元注解)

如何获取spring 注解的bean

SRPING02_配置数据源原始注解开发新注解开发集成Junit代码实现

spring 在哪里可以找到注解的实现代码

Spring组合注解与元注解