Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any API to read property file without Spring in annotation way

I am not using Spring in my application. Is there any API which can load property file into java pojo based on annotation. I am aware of loading properties file using either InputStream Or with Spring's PropertyPlaceHolder. Is there any API using which I can populate my pojo like

@Value("{foo.somevar}")
private String someVariable;

I was unable to find any solution WITHOUT using spring.

like image 834
Sankalp Avatar asked Jan 19 '26 06:01

Sankalp


1 Answers

I come up with a quick hack to bind properties as follows.

Note: It is not optimized, not error-handled. Just showing one possibility.

@Retention(RetentionPolicy.RUNTIME)
@interface Bind
{
    String value();
}

I have tested it some basic params and is working.

class App
{
    @Bind("msg10")
    private String msg1;
    @Bind("msg11")
    private String msg2;

    //setters & getters
}

public class PropertyBinder 
{

    public static void main(String[] args) throws IOException, IllegalAccessException 
    {
        Properties props = new Properties();
        InputStream stream = PropertyBinder.class.getResourceAsStream("/app.properties");
        props.load(stream);
        System.out.println(props);
        App app = new App();
        bindProperties(props, app);

        System.out.println("Msg1="+app.getMsg1());
        System.out.println("Msg2="+app.getMsg2());

    }

    static void bindProperties(Properties props, Object object) throws IllegalAccessException 
    {
        for(Field field  : object.getClass().getDeclaredFields())
        {
            if (field.isAnnotationPresent(Bind.class))
            {
                Bind bind = field.getAnnotation(Bind.class);
                String value = bind.value();
                String propValue = props.getProperty(value);
                System.out.println(field.getName()+":"+value+":"+propValue);
                field.setAccessible(true);
                field.set(object, propValue);
            }
        }
    }
}

Create app.properties in root classpath.

msg10=message1
msg11=message2
like image 200
K. Siva Prasad Reddy Avatar answered Jan 21 '26 23:01

K. Siva Prasad Reddy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!