找不到“ javax.servlet.ServletContext”

时间:2019-04-02 03:08:18

标签: java spring-boot spring-mvc annotations

我有一个Springboot应用程序,如下所示:

@SpringBootApplication
@ImportResource("classpath:/config/applicationContext.xml")
public class TaxBatchMain {

    @Autowired
    TaxIdService taxIdService;

    private static final Logger LOGGER = LogManager.getLogger(TaxBatchMain.class);

    public static void main(String[] args) {

        new SpringApplicationBuilder(TaxBatchMain.class).web(false).run(args);
        TaxBatchMain taxBatchMain = new TaxBatchMain();

    }

    public TaxBatchMain() {

        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);

    }

    @PostConstruct
    public void checkForTransactions() {

        try {
        ////
            String tab = "someother content";

            String footer  = taxIdService.formatFooter();
            ////
            ////
        }catch(){
        //////////

        }
    }

}

TaxIdServiceImpl类如下:

@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class TaxIdServiceImpl implements TaxIdService {


    @Autowired
    private ServletContext servletContext;

     private String formatFooter(String footer) {
        String[] searchList = {"<ENVIRONMENT_NAME>", "<MS_ENV_NAME>"};
        String[] replacementList = {(String) servletContext.getAttribute(ServletContextKey.EMAIL_HOST_NAME.name()),
          (String) servletContext.getAttribute(ServletContextKey.MS_EMAIL_HOST_NAME.name())};

        return StringUtils.replaceEach(footer, searchList, replacementList);
    }

}

应用程序上下文如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"....................///


<context:annotation-config />

    <context:property-placeholder location="classpath:/config.properties" />

    <util:properties id="configProperties" location="classpath:/config.properties" />

  <!--   <context:property-placeholder location="classpath:data/application.properties"/> -->

    <context:component-scan base-package="com.tax.main" /> 
    <context:component-scan base-package="com.tax.service" />
    <context:component-scan base-package="com.tax.model" />
    <context:component-scan base-package="com.tax.mapper" />
    <context:component-scan base-package="com.tax.util" />

    /////

当我运行主类时,我会感到沮丧。错误

申请无法开始


说明:

com.tax.service.TaxIdServiceImpl中的字段ServletContext需要找不到类型为'javax.servlet.ServletContext'的bean。

操作:

考虑在您的配置中定义类型为'javax.servlet.ServletContext'的bean。

1 个答案:

答案 0 :(得分:0)

尝试启用webEnvironment。看来您的SpringApplicationBuilder未在网络环境中启用。

new SpringApplicationBuilder(TaxBatchMain.class).web(true).run(args);

由于您使用的是Spring-boot,因此可以考虑使用基于注释的方法而不是基于xml的方法。