2

In properties file i have 50 questions.

Quest1=1.1
Quest1Text=How are ju?

Quest2=1.2
Quest2Text=How are jui?

Quest3=1.3
Quest3Text=How are juieeeeee?

I want to read them in Java and display in JSP.

Standard way on internet is @Value(ques2)variable @Value(quest2Text) variable But this will make my controller hauch-pauch.

Could you please tell how to assign values to a list in java from properties file using some Spring Annotation?

fatherazrael
  • 5,511
  • 16
  • 71
  • 155

3 Answers3

2

First, you have add property file into your context configuration:

@PropertySource(name = "questions", value = "classpath:question.properties")
public class AppConfig {
   ...
}

I used classpath:prefix in example(that means file will be located in root of class path), but you can use file:, to specify absolute path. Note, that name of source is specified as questions. We will need it in future.

Second, create data container class. Of course, you can use Map<String, String> to store your questions, but class will be more convenient:

public class Quest{
    private String number;
    private String text;

    //getters and setters
    ....
}

Third, get property source in controller and load numbers and values:

@Controller
public class MyController {

    @Autowired
    private ConfigurableEnvironment environment;

    @RequestMapping("/mymapping")
    public String method(ModelMap model){
        List<Quest> questList = loadQuestList();
        model.addAttribute("questList", questList);
        return "myview";
    }    


    private List<Quest> loadQuestList(){

        ResourcePropertySource source = 
            (ResourcePropertySource)environment.getPropertySources().get("questions");

            //first get all names of questions like 'Quest1','Quest2' etc
            List<String> nameList = new ArrayList<String>();
            for(String name : source.getPropertyNames()){
                if(!name.endsWith("Text")){
                    nameList.add(name);
                }
            }
            //unfortunately, default properties are unsorted. we have to sort it
            Collections.sort(nameList);

            //now, when we have quest names, we can fill list of quests
            List<Quest> list = new ArrayList<Quest>();

            for(String name : nameList){
                String number = source.getProperty(name);
                String text = source.getProperty(name+"Text");

                Quest quest = Quest();
                quest.setNumber(number);
                quest.setText(text);
                list.add(quest);
            }
            return list;
    }    
}
Ken Bekov
  • 13,696
  • 3
  • 36
  • 44
1

You can do one thing, all the keys 'QuestX' combine in single key 'Quest' by separating them with some delimiter. Similarly for all the keys starting with 'QuestXText' into another key like 'QuestText'. Then you can use :

    @Value("#{'${Quest}'.split(',')}")
    private List<String> Quest;

    @Value("#{'${QuestText}'.split(',')}")
    private List<Integer> QuestText;

Or you can go with another approach as follows :

public static List<String> getPropertyList(Properties properties, String name) 
{
    List<String> result = new ArrayList<String>();
    for (Map.Entry<Object, Object> entry : properties.entrySet())
    {
        if (((String)entry.getKey()).matches("^" + Pattern.quote(name) + "\\.\\d+$"))
        {
            result.add((String) entry.getValue());
        }
    }
    return result;
}

For more clarity refer : https://stackoverflow.com/a/18654272/3226981

Community
  • 1
  • 1
Suyash
  • 525
  • 1
  • 6
  • 10
1
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class Ex {

    public static void main(String[] args) {

        Properties prop = new Properties();
        InputStream input = null;
        `enter code here`List<String> values=new ArrayList<>();

        try {

            input = new FileInputStream("/application.properties");
            prop.load(input);
            for (int i = 1; i < 50; i++) {
                System.out.println(prop.getProperty("Quest" + i));
                values.add(prop.getProperty("Quest" + i));
            }

        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}