zoukankan      html  css  js  c++  java
  • 获取Spring的Bean

    背景

    这边的例子是使用druid 的 dataSource,默认mybatis已经配置使用了,有些特别语法需要Jdbc执行,不想新建一个dataSource。

    解决方案

    最简单

    在XML配置过的bean可以直接注入使用

    @Autowired
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
    
    <bean id="namedParameterJdbcTemplate"
          class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
        <constructor-arg ref="dataSource"></constructor-arg>
    </bean>
    

    其他

    如果其他原因,不能上面那样写,下面这样就可以获取bean,不会有重复生成的问题。(这里的环境是使用Spring开发RestController)

    WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
    wac.getBean(beanID);
    

    如果是下面这样,Spring配置初始化一次,执行下面代码的时候会再初始化一次,这样就会有两个dataSource,可以在Druid的监控页面上查看具体情况。

    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-context-db.xml");
    DruidDataSource dataSource = (DruidDataSource) applicationContext.getBean("dataSource");
    

    解释

    方法一

    ClassPathXmlApplicationContext
    这样的方式适用于採用Spring框架的独立应用程序,须要程序通过配置文件手工初始化Spring的情况。很多教程上都是按这个来,这个比较适合做Swing的时候用。

    方法二

    ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc); 
    ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc); 
    ac1.getBean("beanId"); 
    ac2.getBean("beanId");  
    

    说明:这样的方式适合于採用Spring框架的B/S系统,通过ServletContext对象获取ApplicationContext对象。然后在通过它获取须要的类实例。上面两个工具方式的差别是,前者在获取失败时抛出异常。后者返回null。

    其他

    https://www.cnblogs.com/yjbjingcha/p/6752265.html

  • 相关阅读:
    Java实现 LeetCode 50 Pow(x,n)
    Java实现 LeetCode 50 Pow(x,n)
    Java实现 LeetCode 49 字母异位词分组
    Java实现 LeetCode 49 字母异位词分组
    Java实现 LeetCode 49 字母异位词分组
    Java实现 LeetCode 48 旋转图像
    Java实现 LeetCode 48 旋转图像
    Java实现 LeetCode 48 旋转图像
    Java实现 LeetCode 47 全排列 II(二)
    Java实现 LeetCode 47 全排列 II(二)
  • 原文地址:https://www.cnblogs.com/my36z/p/9261255.html
Copyright © 2011-2022 走看看