将XML配置导入到基于Java配置(注释)的项目中

10 浏览
0 Comments

将XML配置导入到基于Java配置(注释)的项目中

我正在开发一个基于Spring MVC注解的应用程序。我在web.xml文件中有以下条目(使用WebConfig.java进行配置):


    sdsdispatcher
    org.springframework.web.servlet.DispatcherServlet
    
        contextClass
        org.springframework.web.context.support.AnnotationConfigWebApplicationContext
    
    
        contextConfigLocation
        com.conf.WebConfig
                
    1

现在当我尝试集成与安全相关的XML文件时,我遇到了以下错误

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'springSecurityFilterChain' is defined

at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:638)

我尝试导入XML文件如下:

@Configuration
@EnableWebMvc
@ComponentScan("com.stk.controller")
@ImportResource({"securityContext.xml"})
public class WebConfig extends WebMvcConfigurerAdapter {

截图

enter image description here

https://i.stack.imgur.com/BosWG.jpg

0
0 Comments

问题的出现原因是在Java配置的项目中,无法将XML配置文件导入。

解决方法是通过添加classpath来导入XML配置文件,可以使用以下几种方式:

1. 如果配置文件在classpath中,可以使用以下方式导入:

@ImportResource("classpath:securityContext.xml")

2. 如果有多个配置文件,可以使用以下方式导入:

@ImportResource(locations={"classpath:securityContext.xml","file://c:/test-config.xml"})

3. 如果配置文件在WEB-INF目录中,可以使用以下方式导入:

@ImportResource("file:**/WEB-INF/securityContext.xml")

然而,建议将配置文件移动到src/main/resource目录,并使用classpath加载文件的方式。这些文件在使用maven打包war时会被复制到WEB-INF/classes目录中,这就是classpath。

根据问题描述,尝试了上述方法但都没有成功。请注意,将securityContext.xml文件放在WEB-INF文件夹(在web.xml级别)中。

尝试了("/WEB-INF/securityContext.xml"),仍然没有成功。

对于你遵循的步骤是哪个?是使用文件方式还是像我建议的将文件移动到src/main/resources目录中?

无法直接从WEB-INF目录加载,可以参考以下答案:[stackoverflow.com/a/39998621/156973](https://stackoverflow.com/a/39998621/156973) 和 [stackoverflow.com/a/25936535/156973](https://stackoverflow.com/a/25936535/156973)

0