java org.apache.catalina.core.StandardContext.startInternal 一个或多个监听器启动失败

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45875230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 08:57:30  来源:igfitidea点击:

org.apache.catalina.core.StandardContext.startInternal One or more listeners failed to start

javaspringrestmavencxf

提问by Chaklader Asfak Arefe

I work on a Java/Spring/ Apache Cxfweb app and suddenly, I get the error while I made some apparently naive changes,

我在一个Java/Spring/ Apache Cxf网络应用程序上工作,突然间,当我做了一些明显天真的改变时,我收到了错误,

25-Aug-2017 11:48:43.036 INFO [RMI TCP Connection(2)-127.0.0.1] org.apache.jasper.servlet.TldScanner.scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
log4j:WARN No appenders could be found for logger (org.apache.cxf.common.logging.LogUtils).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
25-Aug-2017 11:48:43.540 SEVERE [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.core.StandardContext.startInternal One or more listeners failed to start. Full details will be found in the appropriate container log file
25-Aug-2017 11:48:43.554 SEVERE [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.core.StandardContext.startInternal Context [] startup failed due to previous errors
[2017-08-25 11:48:43,586] Artifact jaxrs-tutorials:war exploded: Error during artifact deployment. See server log for details.
25-Aug-2017 11:48:49.258 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/Applications/Tomcat-8.5.16/webapps/manager]
25-Aug-2017 11:48:49.310 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/Applications/Tomcat-8.5.16/webapps/manager] has finished in [51] ms

I guess this is the main infoof the error,

我想这是主要info的错误,

25-Aug-2017 11:48:43.540 SEVERE [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.core.StandardContext.startInternal One or more listeners failed to start. Full details will be found in the appropriate container log file
25-Aug-2017 11:48:43.554 SEVERE [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.core.StandardContext.startInternal Context [] startup failed due to previous errors

The project structure is provided,

提供了项目结构,

enter image description here

在此处输入图片说明

The configdirectory is utilized for the Java annotation based configand code is provided below.

config目录用于以下Java annotation based config代码。

The AppConfigfile,

AppConfig文件,

@Configuration
@ComponentScan(AppConfig.SERVICE_PACKAGE)
public class AppConfig {

    public static final String BASE_PACKAGE = "mobi.puut";
    public static final String SERVICE_PACKAGE = BASE_PACKAGE + ".services";
    private static final String RESOURCES_PACKAGE = BASE_PACKAGE + ".rest";
    private static final String PROVIDER_PACKAGE = BASE_PACKAGE + ".rest.provider";

    public static final String API_BASE = "/api/*";

    @ApplicationPath("/")
    public class JaxRsApiApplication extends Application {
    }

    @Bean(destroyMethod = "shutdown")
    public SpringBus cxf() {
        return new SpringBus();
    }

    @Bean
    @DependsOn("cxf")
    public Server jaxRsServer(ApplicationContext appContext) {
        JAXRSServerFactoryBean factory = RuntimeDelegate.getInstance().createEndpoint(jaxRsApiApplication(), JAXRSServerFactoryBean.class);
        factory.setServiceBeans(restServiceList(appContext));
        factory.setAddress("/" + factory.getAddress());
        factory.setProviders(restProviderList(appContext, jsonProvider()));
        return factory.create();
    }

    @Bean
    public JaxRsApiApplication jaxRsApiApplication() {
        return new JaxRsApiApplication();
    }

    @Bean
    public HymansonJsonProvider jsonProvider() {
        return new HymansonJsonProvider();
    }

    private List<Object> restServiceList(ApplicationContext appContext) {
        return RestServiceBeanScanner.scan(appContext, AppConfig.RESOURCES_PACKAGE);
    }

    private List<Object> restProviderList(final ApplicationContext appContext,
                                          final HymansonJsonProvider jsonProvider) {
        final List<Object> providers = RestProviderBeanScanner.scan(appContext, PROVIDER_PACKAGE);
        providers.add(jsonProvider);
        return providers;
    }

}

The WebInitializeris provided,

WebInitializer提供,

public class WebAppInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        servletContext.addListener(new ContextLoaderListener(createWebAppContext()));
        addApacheCxfServlet(servletContext);
    }

    private void addApacheCxfServlet(ServletContext servletContext) {
        CXFServlet cxfServlet = new CXFServlet();

        ServletRegistration.Dynamic appServlet = servletContext.addServlet("CXFServlet", cxfServlet);
        appServlet.setLoadOnStartup(1);

        Set<String> mappingConflicts = appServlet.addMapping(AppConfig.API_BASE);
    }

    private WebApplicationContext createWebAppContext() {
        AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
        appContext.register(AppConfig.class);
        return appContext;
    }

}

I have seen the similar questions to the platform and those don't help me out and I have so little info to solve the issue.

我在平台上看到了类似的问题,但这些问题对我没有帮助,而且我没有多少信息可以解决这个问题。

How can I use loggerto get more info and where I should utilize them? Also, any insight about solving the issue will be helpful. I have updated the JARfiles with mvn clean installand mvn idea:ideacommands.

我怎样才能logger获得更多信息以及我应该在哪里使用它们?此外,任何有关解决问题的见解都会有所帮助。我已经JARmvn clean installmvn idea:idea命令更新了文件。

UPDATE

UPDATE

Tomcat Localhost Log

Tomcat Localhost Log

enter image description here

在此处输入图片说明

Tomcat Catalina Log

Tomcat Catalina Log

enter image description here

在此处输入图片说明

采纳答案by Chaklader Asfak Arefe

I would like to write a detailed answer on the issue and the steps I have followed to solve the problem.

我想写一个关于这个问题的详细答案以及我解决问题所遵循的步骤。

A. There was not enough logging info. I looked up the POMand found this,

A. 没有足够的日志信息。我查了一下POM,发现这个,

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
            <exclusions>
                <!-- Exclude Commons Logging in favor of SLF4j -->
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

I have excluded the logging in the favour of SLF4Jand I just deleted the exclusion XML tag to get more logging info. So, it becomes like this,

我已经排除了日志记录,SLF4J我只是删除了排除 XML 标记以获取更多日志记录信息。于是,就变成这样了

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>

B. Now, I get the logging info. I have this error message like,

B. 现在,我得到了日志信息。我有这样的错误信息,

Caused by: org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name 'userService' for bean class [mobi.puut.services.UserServiceImpl] conflicts with existing, non-compatible bean definition of same name and class [mobi.puut.services.UserService2Impl]

You get the ConflictingBeanDefinitionExceptionfor creating the bean with the same name. Though I have some experience with the Spring, I need to create with a project with the Apache Cxfand hence, clone a demo project for the very purpose. They have the one same entity Userand same definition - interfaceand same implementationof that. Though I have refactoredto all classes in the project and there seem no apparent errors, I still keep an issue - I keep the same bean name "userServicein 2 implementations of the interface.

您将获得ConflictingBeanDefinitionException用于创建具有相同名称的 bean。虽然我与一些经验Spring,我需要用一个项目创建Apache Cxf,因此,克隆演示为根本目的的项目。它们具有相同的实体,User并且相同definition - interface且相同implementation。尽管我必须refactored使用项目中的所有类并且似乎没有明显错误,但我仍然有一个问题 - 我"userService在接口的 2 个实现中保留了相同的 bean 名称。

The User2class in the entities,

User2实体中的类,

public class User2 {

    private Integer id;
    private String name;

    public User2() {
    }

    public User2(Integer id, String name) {
        this.id = id;
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return String.format("{id=%s,name=%s}", id, name);
    }
}

The Userclass in the entities,

User实体中的类,

@Entity
@Table(name = "users")
public class User {

    @Id
    @Column
    @NotNull
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @NotNull
    @Column(name = "name")
    @Size(min = 5, max = 45, message = "Name must be between 5 and 45 characters.")
    private String name;

    public User() {

    }

    public User(int id, String name) {
        super();
        this.id = id;
        this.name = name;
    }

    public User(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof User)) return false;

        User user = (User) o;

        if (getId() != user.getId()) return false;
        return getName().equals(user.getName());
    }

    @Override
    public int hashCode() {
        int result = getId();
        result = 31 * result + getName().hashCode();
        return result;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

The interfaces in the servicesdirectories,

services目录中的接口,

public interface IUserService2 {

    Collection<User2> getUsers();

    User2 getUser(Integer id);

    Response add(User2 user);
}



public interface IUserService {

    List<User> getCurrentStatuses();

    void create(User user);

    List<User> getAllUsers();
}

The implementations of the interfaces inside the servicesderectory,

目录中接口的services实现,

@Service("userService")
public class UserService2Impl implements IUserService2 {

    private static Map<Integer, User2> users = new HashMap<Integer, User2>();

    static {
        users.put(1, new User2(1, "foo"));
        users.put(2, new User2(2, "bar"));
        users.put(3, new User2(3, "baz"));
    }

    public UserService2Impl() {
    }

    @Override
    public Collection<User2> getUsers() {
        return users.values();
    }

    @Override
    public User2 getUser(Integer id) {
        return users.get(id);
    }

    @Override
    public Response add(User2 user) {
        user.setId(users.size()+1);
        users.put(user.getId(), user);

        //do more stuff to add user to the system..
        return Response.status(Response.Status.OK).build();
    }

}


@Service("userService")
public class UserServiceImpl implements IUserService {

    @Autowired
    @Qualifier("userDao")
    public IUserDao userDao;

    public List<User> getCurrentStatuses() {
        return userDao.getAllUsers();
    }

    public void create(User user) {
        userDao.saveOrUpdate(user);
    }

    public List<User> getAllUsers() {
        List<User> users = userDao.getAllUsers();

        if (Objects.isNull(users)) {
            return null;
        }
        return users;
    }
}

And, there was the error- I annotaed 2 classes with the same bean name of "userService". I had to change it like this to provide the bean a different name,

而且,有error- 我用相同的 bean 名称注释了 2 个类"userService"。我不得不像这样改变它来为 bean 提供一个不同的名称,

@Service("user2Service")
public class UserService2Impl implements IUserService2 {

    // some code
}

And, that error goes away. In short, the error ConflictingBeanDefinitionExceptiondue to the 2 beans of the same name and I just had to provide a different name.

而且,那个错误消失了。简而言之,错误是ConflictingBeanDefinitionException由于 2 个 bean 同名而我只需要提供不同的名称。

C. I still had things to fix. Afterwards, when I run the program, I get the

C. 我还有事情要解决。之后,当我运行程序时,我得到

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService': Unsatisfied dependency expressed through field 'userDao'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'mobi.puut.database.IUserDao' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=userDao)}


// some consequent error messages not necessay to solve the issue

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'mobi.puut.database.IUserDao' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=userDao)}

The error here is UnsatisfiedDependencyExceptionand says it can't create a bean with the name of userService. OK, this is the code I had and integrated into the project. The Unsatisfied dependency expressed through the field namely userDao. userDaois the instance of the interface of IUserDaoand it was @autowiredlike this,

这里的错误是UnsatisfiedDependencyException说它不能创建一个名为userService. 好的,这是我拥有并集成到项目中的代码。通过字段表示的 Unsatisfied 依赖即userDaouserDao是接口的实例,IUserDao它是@autowired这样的,

    @Autowired
    public IUserDao userDao;

Here is more insight of the code,

这是代码的更多见解,

@Service("userService")
public class UserServiceImpl implements IUserService {

    @Autowired
    public IUserDao userDao;


     public List<User> getCurrentStatuses() {
        return userDao.getAllUsers();
    }

    public void create(User user) {
        userDao.saveOrUpdate(user);
    }

    public List<User> getAllUsers() {
        List<User> users = userDao.getAllUsers();

        if (Objects.isNull(users)) {
            return null;
        }
        return users;
    }
}

I have an interface in the databasedirectory and consequent implementation of the interface for the user. The interface name is IUserDaoand looks

我在database目录中有一个接口,随后为用户实现了该接口。接口名称是IUserDao和外观

soemthing like this, 


public interface IUserDao {

    boolean create(User user);

    void saveOrUpdate(User user);

    boolean create(List<User> users);

    List<User> getAllUsers();

    User getById(int id);
}

And, the implementation,

而且,实施,

@Repository("userDao")
public class UserDaoImpl implements IUserDao {

    @Autowired
    private SessionFactory sessionFactory;

    // the HQL queries

}

The consequent part of the error message was NoSuchBeanDefinitionExceptionand the app doesn't find a qualifying bean of the type (class) of IUserDao. I have all the HQLqueries in the implementation of the IUserDaoand the code works perfectly before.

错误消息的后续部分是NoSuchBeanDefinitionException,应用程序找不到IUserDao. 我HQL在实现中拥有所有查询,IUserDao并且代码之前运行良好。

I have to take a moment to think and finally, I have an intuition that may be the databaselayer is NOTintegrated into the app. Here is the configurationI used,

我不得不花点时间思考,最后,我有一个直觉,可能是该database层已NOT集成到应用程序中。这是configuration我使用的,

public class WebAppInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        servletContext.addListener(new ContextLoaderListener(createWebAppContext()));
        addApacheCxfServlet(servletContext);
    }

    private void addApacheCxfServlet(ServletContext servletContext) {
        CXFServlet cxfServlet = new CXFServlet();

        ServletRegistration.Dynamic appServlet = servletContext.addServlet("CXFServlet", cxfServlet);
        appServlet.setLoadOnStartup(1);

        Set<String> mappingConflicts = appServlet.addMapping(AppConfig.API_BASE);
    }

    private WebApplicationContext createWebAppContext() {
        AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();

        // register all the config classes here
        appContext.register(AppConfig.class);
        return appContext;
    }

}

Obviously, the no database code is integrated in the WebInitializer. I wrote a new class provides all the info of the database connectionand the hibernate integrationand looks like,

显然,没有数据库代码集成在WebInitializer. 我写了一个新类,提供了database connection和 的所有信息,hibernate integration看起来像,

@Configuration
@EnableWebMvc
@EnableTransactionManagement
@ComponentScan(basePackages = {"mobi.puut.database"})
public class DatabaseConfig {

    @Bean
    public LocalSessionFactoryBean sessionFactory() {

        //  mobi.puut.entities
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(
                new String[]{"mobi.puut.entities"});
        sessionFactory.setHibernateProperties(hibernateProperties());

        return sessionFactory;
    }

    @Bean
    @Autowired
    public HibernateTransactionManager transactionManager(
            SessionFactory sessionFactory) {

        HibernateTransactionManager txManager
                = new HibernateTransactionManager();
        txManager.setSessionFactory(sessionFactory);

        return txManager;
    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
        return new PersistenceExceptionTranslationPostProcessor();
    }

    @Bean
    public DataSource dataSource() {

        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");

        // dataSource.setUrl("jdbc:mysql://localhost:3306/wallet?createDatabaseIfNotExist=true");
        dataSource.setUrl("jdbc:mysql://localhost:3306/Wallet");
        dataSource.setUsername("testuser");
        dataSource.setPassword("testpassword");

        return dataSource;
    }

    Properties hibernateProperties() {

        Properties properties = new Properties();
//        properties.setProperty("hibernate.hbm2ddl.auto", "create-drop");
        properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
        return properties;
    }
}

And, then finally integrate into the WebInitializer. This is the code I used to registeredthe config earlier in the WebInitializer,

并且,然后最终融入到WebInitializer. 这是我之前用于registered配置的代码WebInitializer

appContext.register(AppConfig.class);

Updated the line with the,

更新了行,

appContext.register(AppConfig.class, DatabaseConfig.class);

Finally, everything works fine. So, the configdirectory looks like,

最后,一切正常。所以,config目录看起来像,

enter image description here

在此处输入图片说明

SUMMERY

SUMMERY

I had to solve this problem through the 3 errors,

我不得不通过 3 个错误来解决这个问题,

i. ConflictingBeanDefinitionException
ii. UnsatisfiedDependencyException
iii. NoSuchBeanDefinitionException

ConflictingBeanDefinitionException-> 2 beans with the same name

ConflictingBeanDefinitionException-> 2 个同名豆子

UnsatisfiedDependencyException-> Have a bean (= "userDao")in the class which was not correct to use

UnsatisfiedDependencyException-> 类中有一个(= "userDao")不正确使用的 bean

NoSuchBeanDefinitionException-> the code was correct but needed to add the datbase layer in the congig so the Spring IoCfinds the bean.

NoSuchBeanDefinitionException-> 代码是正确的,但需要在配置中添加 datbase 层,以便Spring IoC找到 bean。

I sincerely hope this will help some people.

我真诚地希望这会帮助一些人。