spring 后置处理器+自定义注解+配置文件

后置处理器

如果我们想在Spring容器中完成bean实例化、配置以及其他初始化方法前后要添加一些自己逻辑处理。我们需要定义一个或多个BeanPostProcessor接口实现类,然后注册到Spring IoC容器中。

代码示例:

package com.test.spring;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
/**
 * bean后置处理器
 * @author zss
 *
 */
public class PostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean,
            String beanName) throws BeansException {
        if ("narCodeService".equals(beanName)) {//过滤掉bean实例ID为narCodeService
            return bean;
        }
        System.out.println("后置处理器处理bean=【"+beanName+"】开始");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean,
            String beanName) throws BeansException {
        if ("narCodeService".equals(beanName)) {
            return bean;
        }
        System.out.println("后置处理器处理bean=【"+beanName+"】完毕!");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return bean;
    }

}

注意:接口中两个方法不能返回null,如果返回null那么在后续初始化方法将报空指针异常或者通过getBean()方法获取不到bena实例对象
     因为后置处理器从Spring IoC容器中取出bean实例对象没有再次放回IoC容器中

自定义注解

注解基础

  1. 注解的定义:Java文件叫做Annotation,用@interface表示。

  2. 元注解:@interface上面按需要注解上一些东西,包括@Retention、@Target、@Document、@Inherited四种。

  3. 注解的保留策略:
      @Retention(RetentionPolicy.SOURCE) // 注解仅存在于源码中,在class字节码文件中不包含
      @Retention(RetentionPolicy.CLASS) // 默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得
      @Retention(RetentionPolicy.RUNTIME) // 注解会在class字节码文件中存在,在运行时可以通过反射获取到

  4. 注解的作用目标:
      @Target(ElementType.TYPE) // 接口、类、枚举、注解
      @Target(ElementType.FIELD) // 字段、枚举的常量
      @Target(ElementType.METHOD) // 方法
      @Target(ElementType.PARAMETER) // 方法参数
      @Target(ElementType.CONSTRUCTOR) // 构造函数
      @Target(ElementType.LOCAL_VARIABLE) // 局部变量
      @Target(ElementType.ANNOTATION_TYPE) // 注解
      @Target(ElementType.PACKAGE) // 包

  5. 注解包含在javadoc中:
      @Documented

  6. 注解可以被继承:
      @Inherited

  7. 注解解析器:用来解析自定义注解。

注解示例

	定义示例 
	@Documented
	@Inherited
	@Target({ ElementType.FIELD, ElementType.METHOD })
	@Retention(RetentionPolicy.RUNTIME)
	public @interface Test{
    	public String value() default "";
	}
	·········································
	使用示例
	public class Persion{
	
	 	private String name;
	 	
	    @Test(value = "value")
	    public void setName(String name)
	    {
	        this.name = name;
	    }
	}
	··········································
	解析示例:
	Method[] methods = Persion.class.getMethods();

        try
        {
            for (Method method : methods)
            {
                // 如果此方法有注解,就把注解里面的数据赋值到user对象
                if (method.isAnnotationPresent(Test.class))
                {
                    Test test= method.getAnnotation(Test.class);
                    {
                    	//做一些想做的事情
                    }
                }
            }
        }

自定义配置文件

配置文件
define.properties

defineTest.pname=test
defineTest.password=test123

代码示例:

package com.kelly.entity;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix="defineTest")
@PropertySource("classpath:define.properties")
public class DefineEntity {
    
    private String pname;
    
    private String password;

    public String getPname() {
        return pname;
    }

    public void setPname(String pname) {
        this.pname = pname;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
    
    
}

实现Spring 从ioc容器获取bean

一般用在非Spring管理的类中使用Spring管理的bean

public class SpringBeanUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    public void setApplicationContext(ApplicationContext applicationContext) 
      throws BeansException {
        SpringBeanUtil.applicationContext = applicationContext;
    }

    public static <T> T getBean(Class<T> clazz) {
        return (T) applicationContext.getBean(clazz);
    }

    public static Object getBean(String name) throws BeansException {

        return applicationContext.getBean(name);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_16773855/article/details/88891436