简体   繁体   中英

How to wire Spring service by interface in parent module?

I'd like to create a parent/framework module and define a service that makes use of some interface methods.

The interface implementation should then be provided by the implementation project. But somehow the injection does not work. Why?

framework module:

package de.test;

    @Service
    public class BaseServiceExecutor {

        @Autowired
        private ICustomService service;

        public void run() {
            service.use();
        }
    }

    interface ICustomService {
        void use();
    }

@Configuration
public class FrameworkAppConfig {

}

implementation module:

package de.test.impl;

@Service
public class MyCustomService implements ICustomService {
    @Override
    void use() {
        //custom impl
    }
}

appContext.xml: (within implementation project)

<context:component-scan base-package="de.test" />

@Configuration
@Import(FrameworkAppConfig.class)
@ComponentScan("de.test")
public class ImplAppConfig

Result:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [IcustomService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

Try adding context:annotation-config to your appContext.xml.

See annotation-config vs component-scan

Your implementation class MyCustomService is not public(unless there is a typo in the code provided). Make it public and spring should pick it up.

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