简体   繁体   中英

Cannot autowire spring session bean by XML config

I have a simple app which is contains xml config, 1 spring session bean, controller. Everything works fine with an annotations, but looks like spring cannot see xml config because it cannot find Person bean?!

The question is how can i autowire beans through xml only?

Exception message:

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>

Bean

//@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;
    }
}

The head of the controller

@Controller
public class HelloController {

    @Autowired
    private Person person;

This answer is based on your comment that you want to know how to do it without the use of annotations.

You can do it without annotations. You need to use the autowire attribute on your bean declaration.

  autowire="byName"

This may be a bit trickier as the @Controller annotation is not configured from xml but this stack overflow post helps explain how you can configure your controller to do so.

This tutorial helps explain the different ways you can autowire from the context file directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM