【问题标题】:set map as a Spring bean将地图设置为 Spring bean
【发布时间】:2017-09-21 13:43:17
【问题描述】:

我需要将地图设置为 spring bean。我有一个使用 @PostConstruct 关键字在 init() 方法中初始化的地图。

public class CustomerService
{

   @Autowired
   TestService testService;

   static Map<String, String> someMap;

     @PostConstruct
     public void initIt() throws Exception {

         someMap = new HashMap<String, String>();
         someMap = // some code by calling testService
     }

     @PreDestroy
     public void cleanUp() throws Exception {}

}

我从 applicationContext.xml 将其称为 bean。

<bean id="customerService" class="test.com.customer.CustomerService"/>

初始化映射工作正常,我需要将此映射的值分配给 bean,以便在应用程序的其他位置访问 bean 的值。

我找到了将地图设置为 bean 的示例,但所有这些都是在 XML 配置中完成的。 How to inject a Map in java springs

我怎样才能完成这项任务。任何知识都受到高度赞赏。

【问题讨论】:

    标签: java spring spring-mvc dictionary


    【解决方案1】:

    您应该为该地图创建一个吸气剂。你可以在其他地方@autowire 你的 bean 并调用 yourbean.getMap() 你就会拥有它。

    在您的其他课程中,您可以:

    @Autowired
    CustomerService customerService;
    

    当然,在您的客户服务中为地图添加一个 getter 方法。 然后在您的控制器或其他服务中,您应该使用上面的注释自动装配您的 bean。然后像这样在你的方法中使用它:

    Map m = customerService.getMap();
    

    您可以稍后使用该方法在您的应用中创建 享元设计模式(当您创建一个 bean 来保存地图时)。 Read a tutorial about Flyweight Design Pattern here


    【讨论】:

    • 谢谢@gen.Strash。我如何自动装配我的 bean?一个示例代码会很棒。再次感谢您
    • 你收到了吗?
    • 谢谢@gen.Strash。我正在看一看。我会更新状态。再次感谢您。
    • 感谢 gen.Strash 提供有效的解决方案。有没有其他方法可以做到这一点?很高兴知道。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-23
    • 1970-01-01
    • 2016-12-07
    • 1970-01-01
    • 2017-09-07
    相关资源
    最近更新 更多