1、MyValue
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyValue {
String value();
}
2、MyValueBeanPostProcess
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
@Component
public class MyValueBeanPostProcess implements BeanPostProcessor {
@Autowired
private Environment environment;
// 要在创建bean 之前
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
// 使用反射给类的属性赋值
Field[] declaredFields = bean.getClass().getDeclaredFields();
for (Field declaredField : declaredFields) {
MyValue annotation = declaredField.getAnnotation(MyValue.class);
if (null == annotation) {
continue;
}
// 去掉private 私有访问权限
declaredField.setAccessible(true);
try {
declaredField.set(bean,environment.resolvePlaceholders(annotation.value()));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}
3、Test2Service
import org.springframework.stereotype.Service;
@Service
public class Test2Service {
@MyValue(value = "${app.port}")
private String name;
@MyValue(value = "${name}")
private String names;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNames() {
return names;
}
public void setNames(String names) {
this.names = names;
}
}
4、App
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;
@ComponentScan
@PropertySource("classpath:app.properties")
public class App {
public static void main( String[] args) {
AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext(App.class);
Test2Service test2Service = (Test2Service) context.getBean("test2Service");
System.out.println(test2Service.getName());
System.out.println(test2Service.getNames());
context.close();
}
}
5、app.properties
name=8080
app.port=123