没有定义SpringApplication源。重写configure方法或添加@Configuration批注

时间:2017-02-09 09:59:44

标签: tomcat spring-boot war

我有一个弹簧启动项目,在此之前我总是将它打包到一个jar文件中并按此运行:
java -jar myjar.jar
现在我想将它转换为war包并将其部署到tomcat中。我跟着这篇文章:
http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#build-tool-plugins-maven-packaging
但当我尝试将其部署到tomcat时,我收到了错误:

2017-02-09 17:26:05.159 [localhost-startStop-1] INFO  s.e.s.devctl.DeviceControllerService - Root context already created (using as parent).
09-Feb-2017 17:26:05.175 SEVERE [localhost-startStop-1] org.apache.catalina.core.ContainerBase.addChildInternal ContainerBase.addChild: start:
 org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/teac-test-0.0.1-SNAPSHOT]]
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:162)
        at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:753)
        at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:729)
        at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
        at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:940)
        at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1816)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalStateException: No SpringApplication sources have been defined. Either override the configure method or add an @Configuration annotation
        at org.springframework.util.Assert.state(Assert.java:392)
        at org.springframework.boot.web.support.SpringBootServletInitializer.createRootApplicationContext(SpringBootServletInitializer.java:124)
        at org.springframework.boot.web.support.SpringBootServletInitializer.onStartup(SpringBootServletInitializer.java:86)
        at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:169)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5303)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
        ... 10 more

09-Feb-2017 17:26:05.190 SEVERE [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Error deploying web application archive C:\work\RCM\CR\apache-tomcat-8.0.39\webapps\teac-test-0.0.1-SNAPSHOT.war
 java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/teac-test-0.0.1-SNAPSHOT]]
        at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:757)
        at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:729)
        at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
        at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:940)
        at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1816)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)

以下是我的主要代码:

@EnableTransactionManagement
@Controller
@EnableAutoConfiguration
@ComponentScan
@RequestMapping("/sdte/teac")
public class TeacService extends SpringBootServletInitializer implements
        EmbeddedServletContainerCustomizer {

    private static final Logger LOGGER = LoggerFactory
            .getLogger(TeacService.class);

    // log file path, the content of the log will be shown in front GUI
    public static final String logFilePath = System.getProperty("logFilePath",
            "teac.log");

    @Autowired
    private InstanceHandler instanceHandler;

    @RequestMapping("/")
    String home() {
        // return stp.html
        return "stp";
    }

    @RequestMapping(value = "/createinstance", method = RequestMethod.POST)
    @ResponseBody
    String createInstance(
            @RequestParam(value = "template") String templateJson,
            @RequestParam(value = "author") String author) {
        LOGGER.debug("User input json: " + templateJson);
        StpTemplate instance = instanceHandler.createInstance(templateJson,
                author);
        if (null != instance) {
            ObjectMapper mapper = new ObjectMapper();
            try {
                LOGGER.info("Successfully created instance "
                        + instance.getInfrastructure().getInstanceName()
                        + ", id="
                        + instance.getInfrastructure().getInstanceId() + "\n");
                return mapper.writeValueAsString(instance);
            } catch (Exception e) {
                e.printStackTrace();
                return "Create instance failed";
            }
        } else {
            return "Create instance failed";
        }
    }

    @RequestMapping(value = "/getallinstances", method = RequestMethod.GET)
    @ResponseBody
    String getAllInstances() {
        List<StpTemplate> instanceList = instanceHandler.getAllInstances();
        ObjectMapper mapper = new ObjectMapper();
        if (null != instanceList && instanceList.size() != 0) {
            try {
                return mapper.writeValueAsString(instanceList);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        } else {
            return "";
        }
    }

    @RequestMapping(value = "/getinstancebyname/{stpname}", method = RequestMethod.GET)
    @ResponseBody
    String getInstanceByName(@PathVariable("stpname") String stpName) {
        LOGGER.info("Try to get instance with name: " + stpName);
        StpTemplate instance = instanceHandler.getInstance(stpName);
        ObjectMapper mapper = new ObjectMapper();
        if (null != instance) {
            try {
                return mapper.writeValueAsString(instance);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        } else {
            return "";
        }
    }

    @RequestMapping(value = "/deleteinstancebyname/{stpname}", method = RequestMethod.DELETE)
    @ResponseBody
    String deleteInstanceByName(@PathVariable("stpname") String stpName) {
        LOGGER.info("Try to delete instance with name: " + stpName);
        if (instanceHandler.removeInstance(stpName)) {
            LOGGER.info("Delete instance " + stpName + " successfully");
            return "Delete instance " + stpName + " successfully";
        } else {
            return "No such instance exists in DB!";
        }
    }

    @RequestMapping(value = "/getinstancebyid/{id}", method = RequestMethod.GET)
    @ResponseBody
    String getInstanceById(@PathVariable("id") int id) {
        LOGGER.info("Try to get instance with id: " + id);
        StpTemplate instance = instanceHandler.getInstance(id);
        ObjectMapper mapper = new ObjectMapper();
        if (null != instance) {
            try {
                return mapper.writeValueAsString(instance);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        } else {
            return "";
        }
    }

    @RequestMapping(value = "/deleteinstancebyid/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    String deleteInstanceById(@PathVariable("id") int id) {
        LOGGER.info("Try to delete instance with id: " + id);
        if (instanceHandler.removeInstance(id)) {
            LOGGER.info("Delete instance " + id + " successfully\n");
            return "Delete instance " + id + " successfully";
        } else {
            return "No such instance exists in DB!";
        }
    }

    @RequestMapping(value = "/getlog", method = RequestMethod.GET)
    @ResponseBody
    String getLog() {
        // File logFile = new File("");
        try {
            return FileUtils.readFileToString(new File(logFilePath));
        } catch (IOException e) {
            e.printStackTrace();
            return "error when reading log file";
        }
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(TeacService.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(
            SpringApplicationBuilder builder) {
        return builder.sources(TeacService.class);
    }

    @Bean(name = "datasource")
    public DataSource dataSource() {
        // default value
        String url = "jdbc:neo4j:http://localhost:7474";
        String user = "neo4j";
        String password = "pdbb";
        // get the expected value from configuration file
        if (ConfigurationUtils.getValue("neo4j", "url") != null) {
            url = (String) ConfigurationUtils.getValue("neo4j", "url");
        }
        if (ConfigurationUtils.getValue("neo4j", "user") != null) {
            user = (String) ConfigurationUtils.getValue("neo4j", "user");
        }
        if (ConfigurationUtils.getValue("neo4j", "password") != null) {
            password = (String) ConfigurationUtils
                    .getValue("neo4j", "password");
        }
        return new DriverManagerDataSource(url, user, password);
    }

    @Bean
    @Autowired
    public PlatformTransactionManager transactionManager(
            @Qualifier("datasource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Autowired
    JdbcTemplate jdbc;

    @Autowired
    private PlatformTransactionManager transactionManager;

    @RequestMapping(value = "/test", method = RequestMethod.POST)
    @ResponseBody
    @Transactional
    String test() {
        jdbc.execute("match (du:RESOURCE{name:'DU-20'})-[c:Connects{name:'connection'}]->(xc) set du.type = 'BB5216'");
        // transactionManager.
        TransactionStatus status = transactionManager.getTransaction(null);
        jdbc.execute("match (du:RESOURCE{name:'DU-20'})-[c:Connects{name:'connection'}]->(xc) set  du.type = 'BB5217'");
        transactionManager.commit(status);
        return null;
    }

    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {
        // default value is 8080
        int port = 8080;
        // get the expected value from configuration file
        if (ConfigurationUtils.getValue("port", "teac") != null) {
            port = (int) ConfigurationUtils.getValue("port", "teac");
        }
        container.setPort(port);
    }
}

任何可以帮助我的人?提前谢谢!

3 个答案:

答案 0 :(得分:1)

就我而言,我有两个类在Spring Boot扫描的同一包中扩展了'SpringBootServletInitializer'。即使删除其中一个类的@SpringBootApplication或@ComponentScan也无效。只留下一个类,经过编译后它又可以工作了。

答案 1 :(得分:0)

添加@SpringBootApplication或@Configuration TeacService类,它将对我来说很好用,请检查该答复是否对您不起作用。

答案 2 :(得分:-2)

由于我的部署在公司平台上,我的问题解决了,因为项目的解包地址不正确