我正在尝试编写代码来注释类中的字段,以便从配置文件中设置该字段的值。这实际上与spring框架具有的@Value属性相同,但由于我不会进入的原因,我没有使用spring框架。
我正在开发的项目是使用Jersey框架的Web应用程序。我为所有前期信息道歉,但为了完整起见,这里是我所拥有的基本设置:
这是主要的应用程序类:
package com.ttrr.myservice;
import com.ttrr.myservice.controllers.MyController;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import java.util.HashSet;
import java.util.Set;
@ApplicationPath("/")
public class MyApplication extends Application {
@Override
public Set<Class<?>> getClasses() {
final Set<Class<?>> classes = new HashSet<Class<?>>();
// register root resources
classes.add(MyController.class);
return classes;
}
}
这是我想要注释的MyController类:
package com.ttrr.myservice.controllers;
import com.ttrr.myservice.annotations.Property;
import javax.servlet.ServletContext;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
@Path("test")
public class MyController {
@Property("my.value.from.config")
private String myValue;
@GET
@Produces("text/html")
@Path("/testPage")
public String testPage(@Context ServletContext context) {
return "<p>" + myValue + "</p>";
}
}
我的注释界面非常简单:
package com.ttrr.myservice.annotations;
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 Property {
String value() default "";
}
我有一个注释解析器类:
package com.ttrr.myservice.annotations;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Properties;
public class PropertyParser {
public static Properties properties;
static {
properties = new Properties();
try {
Property.class.getClassLoader();
Properties defaults = new Properties();
defaults.load(Property.class.getClassLoader().getResourceAsStream("application.properties"));
for(Object key : defaults.keySet()) {
properties.put(key, defaults.get(key));
}
} catch (IOException e) {
//in this case do nothing, properties will simply be empty
}
}
public void parse(Class<?> clazz) throws Exception {
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(Property.class)) {
Property property = field.getAnnotation(Property.class);
String value = property.value();
if (!"".equals(value)) {
field.set(clazz, properties.getProperty(value));
}
}
}
}
}
我真正挣扎的是将它们放在一起,并将我的application.properties文件中的值从MyController类的实例中获取。
感谢您花时间阅读所有内容!任何帮助将不胜感激。
答案 0 :(得分:3)
您尝试设置值的方式不正确,因为您需要一个实例来设置值。
field.set(clazz, properties.getProperty(value));
应该是:
field.set(instance, properties.getProperty(value));
你应该为你的解析方法添加一个参数:
public void parse(Class<?> clazz, Object instance) throws Exception {