【问题标题】:Cannot autowire spring session bean by XML config无法通过 XML 配置自动装配 Spring 会话 bean
【发布时间】:2018-09-18 06:17:48
【问题描述】:

我有一个简单的应用程序,其中包含 xml 配置、1 个弹簧会话 bean、控制器。使用注释一切正常,但看起来 spring 看不到 xml 配置,因为它找不到 Person bean?!

问题是如何仅通过 xml 自动装配 bean?

异常信息:

No qualifying bean of type 'com.spring_beans_scope.beans.Person' available: expected at least 1 bean which qualifies as autowire candidate
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="id1" class="com.spring_beans_scope.beans.WelcomeBean" scope="prototype">
        <!--<property name="message" value="Welcome to spring" />-->
    </bean>

    <bean id="person" class="com.spring_beans_scope.beans.Person" scope="session">
        <property name="name" value="Raj" />
        <aop:scoped-proxy proxy-target-class="true" />
    </bean>

    <context:component-scan base-package="com.spring_beans_scope" />
    <context:annotation-config />
</beans>

豆子

//@Service("person")
//@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class Person {

    private String name;

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

控制器的头部

@Controller
public class HelloController {

    @Autowired
    private Person person;

【问题讨论】:

  • ....你为什么要连接 POJO?你想做什么?
  • 个人不是服务。这是一个 POJO。您不应该将 POJO 自动装配到控制器或任何类中。
  • 问题是为什么我可以用注释来做到这一点而没有它们就不行?!
  • 我试图像在这个例子中那样做任务knowledgewalls.com/j2ee/books/spring-30-examples/…

标签: java spring spring-mvc


【解决方案1】:

此答案基于您想知道如何在不使用注释的情况下执行此操作的评论。

你可以在没有注释的情况下做到这一点。您需要在 bean 声明中使用 autowire 属性。

  autowire="byName"

这可能有点棘手,因为 @Controller 注释不是从 xml 配置的,但 this 堆栈溢出帖子有助于解释如何配置控制器来执行此操作。

这个tutorial 有助于解释直接从上下文文件自动装配的不同方法。

【讨论】:

  • 我不确定它是否与 Spring 会话 bean 相关联。有一个包含两个 bean 的示例:原型和默认(单例)。我没有 WebAppConfig,但我认为这对我来说是不必要的
猜你喜欢
  • 2016-09-27
  • 1970-01-01
  • 2012-12-04
  • 2015-08-06
  • 2015-12-23
  • 2020-09-09
  • 2018-06-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多