使用注解属性绑定

你们应该知道在Spring中有一个注解@Value,他能够帮助咱们来说Spring加载的配置文件(*.perperties)文件中的信息自动的注入到咱们的非静态属性中的。java

通常状况下咱们会这样使用:ide

1.  首先在Spring的配置文件中加载属性文件:函数

<context:property-placeholder location="classpath:component.properties"  ignore-unresolvable="true"/>

而后在Java代码中使用@Value注解就能够注入值了,好比:测试

 
@Value("${open_office_install_home}")
private String openOfficeInstallHome;
 
固然属性若是是static的话是不能注入的。
 
其实这个自动注入的过程实现起来比较简单,咱们下面经过一个例子来大体描述一下这个原理吧,这个例子是我写的,并不表明Spring的源码就是这么实现的。可是原理是同样的。
 
1.  咱们先自定义一个注解:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Value {

    public String value();

}

2. 而后新增一个处理类:this

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Properties;


public class PropertyInvokationHandler implements InvocationHandler {

    private Properties properties;

    public PropertyInvokationHandler(Properties properties) {
        this.properties = properties;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Value annotation = method.getAnnotation(Value.class);
        if(annotation == null){
            throw new RuntimeException(String.format("Method:{} is not bound to a property.", method.getName()));
        }
        return properties.getProperty(annotation.value());
    }
}

3.  建立一个公共方法:spa

import java.lang.reflect.Proxy;
import java.util.Properties;

public class PropertyTool {

    private PropertyTool() {
    }

    public static <T> T bindProperties(Class<T> clazz, Properties properties) {
        return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{clazz},
                new PropertyInvokationHandler(properties));
    }
}

这样咱们就完成了这个功能了。component

 

下面咱们经过测试代码来验证一下咱们的功能是否起做用:orm

咱们建立一个接口:blog

public interface UserService {

    @Value("user.name")
    public String getUserName();

    @Value("user.password")
    public String getPassword();

}

而后编写测试类:接口

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class UserServiceTester {

    public static void main(String[] args) {
        Properties properties = new Properties();

        try {
            String path = UserServiceTester.class.getResource("/user.properties").getPath();
            InputStream in = new FileInputStream(path);
            properties.load(in);
            in.close();
        } catch(IOException ex) {
            ex.printStackTrace();
        }

        UserService config = PropertyTool.bindProperties(UserService.class, properties);
        System.out.println("User Name: " + config.getUserName());
        System.out.println("Password: " + config.getPassword());
    }
}

而咱们的user.properties属性文件中的内容为:

user.name=rollenholt
user.password=123

运行上面的main方法,就会输出属性文件中的内容了。

 

不知道你们有没有注意到,咱们在测试代码中使用的UserService是一个接口,咱们并无建立他的实现类,可是咱们在main函数中依旧能够钓鱼他的方法。那是由于在运行时自动生成了一个实现。是否是觉的这个功能能够用在不少的地方呀。

相关文章
相关标签/搜索