【问题标题】:Modifying Servlet.xml of Spring修改Spring的Servlet.xml
【发布时间】:2014-07-27 12:36:04
【问题描述】:

下面是我的servlet.xml。我需要添加以下节点

<bean id="myController2"class="com.restcontrollers.MyController2"></bean>

在运行时到这个 xml。 这可能吗?如果可以,怎么做?

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

<context:component-scan base-package="com.restcontrollers"/>

  <bean id="myController1"class="com.restcontrollers.MyController1">
  </bean>

<mvc:annotation-driven />
</beans>

我们将不胜感激任何形式的帮助。 提前致谢。

【问题讨论】:

  • 你想要完成什么?根据您尝试做的事情,可能会有更好的可行解决方案
  • 您可以添加该行,但不会重新读取配置。
  • 感谢您的帮助。实际上我正在尝试在运行时加载新控制器。

标签: xml spring servlets


【解决方案1】:

您有三个选择:

选项 1: 如果可以在 bean 定义 xml 中配置 bean 并且可以在运行时在第一次请求时完成实例化,则可以使用 lazy-init 属性创建 myController2:

    <bean id="myController2" class="com.restcontrollers.MyController2" lazy-init="true"></bean>

您可以在here找到更多详细信息。

选项 2: 通过使用 Spring AOP @Configurable 注解,该注解将一个类标记为符合 Spring 驱动配置的条件(如使用“new”运算符实例化的对象)。

    @Configurable
        public class MyController2 {
        ...
        }

并指定这个

    <context:spring-configured/>

在 servlet.xml 中。 你可以找到更多关于这个spring aop方式的信息here

选项 3: 在要调用新的 myController2 的类中: 访问 applicationContext 并创建 bean:

    ApplicationContext ctx = new ClassPathXmlApplicationContext("servlet.xml");
    MyController2 myController2 = new MyController2();
    ctx.getAutowireCapableBeanFactory().autowireBeanProperties(myController2, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);

【讨论】:

    猜你喜欢
    • 2013-04-11
    • 1970-01-01
    • 1970-01-01
    • 2011-04-08
    • 2011-03-30
    • 2018-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多