简体   繁体   中英

Accessing spring configured HashMap from applicationContext inside any classes in the Project

Trying to create (Key,Value) pair ie, HashMap in the applicationContext and trying access it from a class through @Resource annotation.

But it is unable to inject hashMap and getting null in the @Resource variable.

ApplicationContext :

<bean id="explicitWaitTime" class="java.util.HashMap">
    <constructor-arg>
        <map key-type="java.lang.String" value-type="java.lang.String">
            <entry key="COSCO" value="15"/>
            <entry key="Hamburg" value="15"/>
         </map>
    </constructor-arg>
</bean>

Business Class :

public class BusinessClass implements IBusinessClass {    

@Resource 
private Map<String, String> explicitWaitTime;

@Override 
public void getExplicitWaitMaps() {  // From IBusinessClass interface

System.out.println("ExplicitWaitTime " +     
explicitWaitTime.get("COSCO"); //explicitWaitTime is null

}    
}

Multiple ways to inject:

  • In your application context file, define another bean for your business class and using constructor or setter injection, inject a hashmap. For this, you will have to provide either parameterized constructor or a property setter depending upon if it can work with or without hashmap.
  • use Auto wired annotation

用@Component注释BusinessClass类,然后让spring容器实例化它。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM