名称[jdbc / springmvc]在此上下文中未绑定

时间:2019-03-26 06:42:20

标签: mysql spring-mvc

*org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'webConfig': 
Unsatisfied dependency expressed through field 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'getDataSource' defined in com.futor.user.config.WebConfig: 
Bean instantiation via factory method failed; nested exception is 
org.springframework.beans.BeanInstantiationException: 
Failed to instantiate [javax.activation.DataSource]: 
Circular reference involving containing bean 'webConfig' - consider declaring the factory method as static for independence from its containing instance. Factory method 'getDataSource' threw exception; nested exception is javax.naming.NameNotFoundException: 
Name [jdbc/springmvc] is not bound in this Context. Unable to find [jdbc].
    at  org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
    at  org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
    at  org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)
    at  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1395)
    at  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592)
    at  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
    at  org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
    at  org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at  org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
    at  org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at  org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:849)
    at  org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877)
    at  org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
    at  org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:400)
    at  org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:291)
    at  org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:103)
    at  org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5155)
    at  org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5680)
    at  org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at  org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:1018)
    at  org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:994)
    at  org.apache.catalina.core.StandardHost.addChild(StandardHost.java:652)
    at  org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:1127)
    at  org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:2021)
    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:1149)
    at  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at  java.lang.Thread.run(Thread.java:748) 
    Caused by: org.springframework.beans.factory.BeanCreationException: 
    Error creating bean with name 'getDataSource' defined in com.futor.user.config.WebConfig: 
    Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: 
    Failed to instantiate [javax.activation.DataSource]: Circular reference involving containing bean 'webConfig' - consider declaring the factory method as static for independence from its containing instance. Factory method 'getDataSource' threw exception; nested exception is javax.naming.NameNotFoundException: 
    Name [jdbc/springmvc] is not bound in this Context. Unable to find [jdbc].
    at  org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:627)
    at  org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:456)
    at  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1305)
    at  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1144)
    at  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
    at  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
    at  org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
    at  org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at  org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
    at  org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at  org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277)
    at  org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1247)
    at  org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1167)
    at  org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593)

WebConfig.java:

@Configuration@EnableWebMvc@ComponentScan(basePackages = {
    "com.futor.user"
})

public class WebConfig extends WebMvcConfigurerAdapter {

    @Autowired
    DataSource dataSource;

    @Bean
    public NamedParameterJdbcTemplate namedParameterJdbcTemplate() {
        return new NamedParameterJdbcTemplate((javax.sql.DataSource) dataSource);
    }

    @Bean
    public DataSource getDataSource() throws NamingException {
        JndiTemplate jndiTemplate = new JndiTemplate();
        DataSource dataSource = (DataSource) jndiTemplate.lookup("java:comp/env/jdbc/springmvc");
        return dataSource;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry handlerRegistry) {
        handlerRegistry.addResourceHandler("/resources/**").addResourceLocations("/resources");
    }

    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/jsp/user");
        viewResolver.setSuffix(".jsp");
        return null;
    }   
}

pom.xml:

<dependencies>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.1.5.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>5.1.5.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
        <scope>provided</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.1.5.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
</dependencies>
<build>
    <finalName>test</finalName>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.6</version>
            <configuration>
                <failOnMissingWebXml>false</failOnMissingWebXml>
            </configuration>
        </plugin>
    </plugins>
</build>

WebInitiallizer.java:

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class WebInitiallizer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class < ?>[] getRootConfigClasses() {
        // TODO Auto-generated method stub
        return new Class[] {
            WebConfig.class
        };
    }

    @Override
    protected Class < ?>[] getServletConfigClasses() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    protected String[] getServletMappings() {
        // TODO Auto-generated method stub
        return new String[] {
            "/"
        };
    }
}

1 个答案:

答案 0 :(得分:0)

出现此问题是因为由于jndi查找失败而导致此bean的自动装配失败。试试这个:

    <mvc:View xmlns:core="sap.ui.core" xmlns:l="sap.ui.layout" xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m"
        xmlns:html="http://www.w3.org/1999/xhtml" xmlns:f="sap.ui.layout.form" controllerName="hmel.TravelandGuestHouse.controller.BookMeal">
        <Page title="Book your meal !" showNavButton="true" navButtonPress="_onNavBack">
            <VBox renderType="Bare" class="sapUiMediumMargin" justifyContent="Center" id="textVBox">
                <Text id="changeText" textAlign="Center" width="100%"/>
            </VBox>
            <VBox class="sapUiSmallMargin" direction="Column" alignItems="Center" justifyContent="Center">
                <f:SimpleForm class="form" editable="true" layout="ResponsiveGridLayout" labelSpanXL="4" labelSpanL="4" labelSpanM="4" labelSpanS="12"
                    emptySpanXL="3" emptySpanL="3" emptySpanM="3" emptySpanS="0" width="100%">
                    <f:content>
                        <Label text="Meal from date" required="true"/>
                        <DatePicker id="fromDate" class="disablekb input" change="onFromDateSelect"/>
                        <Label text="Meal to date"/>
                        <DatePicker id="toDate" class="disablekb input" change="toDateChange"/>
                        <Label text="Meal" required="true"/>
                        <ComboBox id="meal" items="{ path: 'Model>/value', filters: [{ path: 'MealField', operator: 'NE', value1: null }] }"
                            selectionChange="onMealChanged">
                            <core:Item xmlns:core="sap.ui.core" key="{Model>ID}" text="{Model>MealField}"/>
                        </ComboBox>
                        <Label text="Location" required="true"/>
                        <ComboBox id="location"
                            items="{ path: 'LocModel>/locValue', filters: [{ path: 'LocationFieldNew', operator: 'NE', value1: null }], sorter: { path: 'LocationFieldNew' } }"
                            selectionChange="onLocationChanged">
                            <core:Item xmlns:core="sap.ui.core" key="{LocModel>ID}" text="{LocModel>LocationFieldNew}"/>
                        </ComboBox>
                        <Label text="Meal Type" required="true"/>
                        <ComboBox id="mealType" selectedKey="{mTypeModel>/mTypeValue/0/ID}"
                            items="{ path: 'mTypeModel>/mTypeValue', filters: [{ path: 'MealTypeFieldNew', operator: 'NE', value1: null }] }"
                            selectionChange="onMealTypeChanged">
                            <core:Item xmlns:core="sap.ui.core" key="{mTypeModel>ID}" text="{mTypeModel>MealTypeFieldNew}"/>
                        </ComboBox>
                        <Label text="Diet" id="dietLabel" required="true" visible="false"/>
                        <ComboBox id="diet" visible="false">
                            <items>
                                <core:Item xmlns:core="sap.ui.core" key="1" text="Veg"/>
                                <core:Item xmlns:core="sap.ui.core" key="2" text="NonVeg"/>
                            </items>
                        </ComboBox>
                        <Label text="Quantity"/>
                        <Input value="1" id="quantity" editable="false"/>
                        <Label text="Remarks"/>
                        <TextArea width="100%" rows="4" id="remarks" placeholder="An increase/decrease in Chapati/Rice/Veg to be mentioned here." growing="true"
                            cols="40"/>
                    </f:content>
                </f:SimpleForm>
                <!--    </VBox>-->
                <Label text="Notes : " width="100%" id="label13" textAlign="Center" design="Bold"/>
                <!--<VBox class="sapUiSmallMarginBeginEnd sapUiSmallMarginEnd" alignContent="Start" alignItems="Center" renderType="Bare" width="100%" displayInline="true" justifyContent="Center" wrap="Wrap">-->
                <Label text="Breakfast : to be booked atleast one day prior before 2359 hrs." wrapping="true" class="sapUiSmallMarginTop"/>
                <Label text="Lunch (Veg and Non Veg) : to be booked before 1130 hrs. of that particular day,booking opened for later days."
                    class="sapUiSmallMarginTop" wrapping="true"/>
                <Label text="Eve Snacks: To be booked before 1630 hrs. of that particular day,booking opened for later days." class="sapUiSmallMarginTop"
                    wrapping="true"/>
                <Label text="Dinner (Veg and Non veg) : to be booked before 1800 hrs. of that particular day ,booking opened for later days"
                    class="sapUiSmallMarginTop" wrapping="true"/>
                <Label text="Midnight Snacks: To be booked by 2359 hrs. of that particular day for next day ,booking opened for later days"
                    class="sapUiSmallMarginTop" wrapping="true"/>
                <Label text="Non Veg will only be served on Friday in lunch and dinner" class="sapUiSmallMarginTop sapUiSmallMarginBottom" wrapping="true"/>
            </VBox>
            <footer>
                <Bar>
                    <contentRight>
                        <Button text="Cancel" type="Reject" id="cancel" press="onCancel"/>
                        <Button text="Order" type="Accept" press="onSubmit" id="submit"/>
                    </contentRight>
                    <contentMiddle/>
                </Bar>
            </footer>
            <content/>
        </Page>
    </mvc:View>