java - 避免 Spring ApplicationContext 实例化

标签 java spring spring-mvc

我使用Spring 3做了一个简单的配置。

我有一个名为 PropertyBeans.xml 的 XML 文件:

<bean id="propertyBean" class="com.myapp.PropertyBean">
    <property name="rootDirLogPath" value="C:\Users\dede" />
</bean>

我有一个匹配这个 XML 的 bean,然后我想使用这个 bean 和注入(inject)的值。其实我有:

ApplicationContext context = new ClassPathXmlApplicationContext("AppPropertyBeans.xml");
PropertyBean obj = (PropertyBean) context.getBean("propertyBean");
String rootDirLogPath = obj.getRootDirLogPath();

这很好用,但我想知道是否有一种方法可以避免每次我想使用 bean 时都实例化 ApplicationContext。我听说过 BeanFactory 是个好主意吗?还有哪些解决方案?

换句话说:我是否应该在 spring MVC 中的每个 Controller 中调用这个应用程序上下文实例化?

最佳答案

如果你想在 Controller 中使用 spring bean,在 applicationContext.xml 中添加一行:

<context:spring-configured/>
<task:annotation-driven/>
<context:component-scan base-package="by" />

然后按照以下方式编写您的 Controller :

@Controller
public class IndexController {

    @Autowired
    private UserService userService;

    @Autowired
    private GroupService groupService;

        // methods with @RequestMapping annotation
}

这是微不足道的事情,所以如果您有任何疑问,强烈建议阅读“Spring in action book”,第 7 章:构建 Web 应用程序

关于java - 避免 Spring ApplicationContext 实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18188562/

相关文章:

java - 在java中连接到共享驱动器

java.io.IOException : unexpected end of stream on okhttp3. 地址@46888237

java - C# 等效于 Java 的 BreakIterator

java - 所有 Spring beans 都是代理的吗?

java - Autowiring SimpMessagingTemplate

java - 将日期增加一天,但同时以某种方式将月份减少 1

java - Spring Eureka 服务器在客户端 url 中找不到上下文路径

java - 如何使用 Spring Boot 注册辅助 servlet?

java - Spring无法创建bean

java - 如何处理在服务器上上传的视频 block 和用 Spring mvc 编写的服务器代码