Spring组件扫描的bean无法访问。

8 浏览
0 Comments

Spring组件扫描的bean无法访问。

我有一个被@Service注解的UserDetailsService类。我还有被注解的DAO类,在我的控制器中自动装配并正常工作。

问题是,当我想在security-context.xml中连接UserDetailsService bean时,Spring找不到该bean。是否是因为我的component-scan在controllers.xml文件中,超出了安全配置的范围之外?

xml配置文件布局如下:

web.xml:


    contextConfigLocation
        
              /WEB-INF/spring/root-context.xml
              /WEB-INF/spring/appServlet/security-context.xml
        

servlet-context.xml:

...

...

0
0 Comments

问题出现的原因:在Spring中,当我们使用@ComponentScan注解扫描bean时,需要将该注解添加到所有需要访问这些bean的上下文中,而不仅仅是一个上下文。

解决方法:将@ComponentScan注解添加到所有需要访问这些bean的上下文中,而不仅仅是一个上下文。

下面是解决该问题的示例代码:

@Configuration
@ComponentScan("com.example.package")
public class AppConfig {
    // Configuration code...
}

@Configuration
@ComponentScan("com.example.package")
public class WebConfig {
    // Configuration code...
}

在上面的示例中,我们在两个不同的上下文(AppConfig和WebConfig)中都添加了@ComponentScan注解,以确保这两个上下文都能访问到被扫描的bean。

这样做可以避免出现"Spring Component scanned bean not accessable"这个问题。

0