首先springboot 已经不推荐使用xml文件了,如果要使用那么请接着往下看。
如果一定要使用,可以通过@ImportResource注解来完成。 首先注释掉ServletConfig.java中的@Configuration
package com.shiyanlou.springboot.config;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Configuration;
//@Configuration
public class ServletConfig implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
@Override
public void customize(ConfigurableServletWebServerFactory factory) {
//设置端口
factory.setPort(8080);
}
}
接着在src/main/resources/中建立xml文件config.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="servletConfig" class="com.shiyanlou.springboot.config.ServletConfig"/>
</beans>
然后在SpringbootApplication.java修改为如下形式:
package com.shiyanlou.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
//通过@ImportResource加载xml配置文件
@ImportResource(value = "classpath:config.xml")
@SpringBootApplication
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
}
接着重启项目,如果可以成功访问,那么说明成功的导入了xml配置。