标签: spring-annotations

创建名为“resourceHandlerMapping”的 bean 时出错

我有一个带有 spring 的应用程序,它使用 JpaConfiguration 类来处理我的数据库,并使用 WebAppMvcConfigurer 类通过 json 消息处理前端。两者都有一个@Configuration并且位于同一个包中。我的根包中有一个 App 类,其中包含 @Configuration 和 @ComponentScan 以及我的 main 方法。

当我启动 App 类时,出现此错误:

    Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'resourceHandlerMapping' defined in class path resource [org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'resourceHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException: No ServletContext set
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:656)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:636)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at …
Run Code Online (Sandbox Code Playgroud)

java spring spring-annotations

6
推荐指数
1
解决办法
2万
查看次数

VSCode、Gradle、Spring Boot、无法导入 javax.validation

全部。
我想在 spring boot(2.3.0) 框架中使用 @Valid 和 @NotEmpty 。
但我无法导入,javax.validation所以我不能。这是我当前遇到的
屏幕和文件:build.gradle

  1. 不能使用@Valid注解在此输入图像描述
  2. 不能使用@NotEmpty注解在此输入图像描述

<文件:build.gradle>

plugins {
    id 'org.springframework.boot' version '2.3.0.RELEASE'
    id 'io.spring.dependency-management' version '1.0.9.RELEASE'
    id 'java'
}

group = 'kr.co.fastcampus'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

configurations {
    developmentOnly
    runtimeClasspath {
        extendsFrom developmentOnly
    }
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    //  Spring Boot
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-validation'

    //  Database
    implementation 'com.h2database:h2'

    compileOnly 'org.projectlombok:lombok'

    developmentOnly 'org.springframework.boot:spring-boot-devtools'

    annotationProcessor 'org.projectlombok:lombok'

    testImplementation 'org.springframework.boot:spring-boot-starter-test' …
Run Code Online (Sandbox Code Playgroud)

java spring-annotations spring-boot

6
推荐指数
2
解决办法
6434
查看次数

如何在 Spring 中禁用使用 @Component 注释创建 bean?

我的项目中有一些用于重构逻辑的通用接口。它看起来大约是这样的:

public interface RefactorAwareEntryPoint {

    default boolean doRefactor() {
        if (EventLogService.wasEvent(getEventType())) {
            return true;
        }
        boolean result = doRefactorInternal();
        if (result) {
            EventLogService.registerEvent(eventType);
        }
        return result;
    }

    String getEventType();
    
    boolean doRefactorInternal();
}
Run Code Online (Sandbox Code Playgroud)

然后,当我需要编写一些重构时 - 我使用方法实现此接口,标记类@Component,然后 Spring 循环评估每个接口实现并将其注册到数据库中。但我们有很多重构(每年 - 200-300 个新重构)。手动禁用旧的实现很困难,而且我们的 spring 上下文中有很多 bean。我们可以做一些事情,例如,使用一些注释 - 这将在某些条件下禁用组件创建?

例如:

@Component
@Enabled(YEAR.2020)
public class CustomRefactor implements RefactorAwareEntryPoint {
 // Code implementation
}
Run Code Online (Sandbox Code Playgroud)

这个注释将像这样工作(伪代码):

if (YEAR.2020) {
  create bean -> new CustomRefactor()
}
Run Code Online (Sandbox Code Playgroud)

当它到来时YEAR.2021,我们将不会在 spring-context 中得到任何豆子YEAR.2020

java spring spring-annotations spring-boot

6
推荐指数
2
解决办法
2万
查看次数

将基于Spring的Spring转换为基于Java的配置

我尽量不使用任何xml.

<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">

    <property name="messageConverters">
        <list>
            <bean class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
                <property name="marshaller" ref="jaxbMarshaller"/>
                <property name="unmarshaller" ref="jaxbMarshaller"/>
            </bean>
            <bean class="org.springframework.http.converter.FormHttpMessageConverter"/>
        </list>
    </property>
</bean>
Run Code Online (Sandbox Code Playgroud)

像这样:转换为@Bean

@Bean
public RestTemplate restTemplate() {
    RestTemplate restTemplate = new RestTemplate();
    List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();

    converters.add(marshallingMessageConverter());
    restTemplate.setMessageConverters(converters);

    return restTemplate;
}
Run Code Online (Sandbox Code Playgroud)

问题在这里.

<bean id="jaxbMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
    <property name="classesToBeBound">
        <list>
            <value>com.cloudlb.domain.User</value>
        </list>
    </property>
</bean>
Run Code Online (Sandbox Code Playgroud)

尝试将"com.cloudlb.domain.User"转换为Class []而不是工作.

@Bean
public MarshallingHttpMessageConverter marshallingMessageConverter() {
    Jaxb2Marshaller marshaller = new Jaxb2Marshaller();

    //
    List<Class<?>> listClass = new ArrayList<Class<?>>();
    listClass.add(User.class);

    marshaller.setClassesToBeBound((Class<?>[])listClass.toArray());
    // --------------------------------

    return new MarshallingHttpMessageConverter(marshaller, marshaller);
} …
Run Code Online (Sandbox Code Playgroud)

java xml configuration spring spring-annotations

5
推荐指数
1
解决办法
1万
查看次数

在Spring 3.1中,<mvc:interceptors>可以与@Configuration一起使用

我从Spring 3.0.5迁移到3.1,因为我需要自定义RequestMappingHandlerMapping.我在扩展RequestMappingHandlerMapping的插件中遇到问题 - 我有现有的servlet-conetxt.xml,我添加了带有@Configuration注释的WebConfig.但是,我总是得到错误ambiguos映射(因为在ExtendedRequestMappingHandlerMapping中定义的新注释不是takign生效).

我在servlet-context.xml中定义了各种级别的拦截器,我想保留在XML配置中.我想用.

有没有办法使用servlet-context.xml的连接,同时扩展RequestMappingHandlerMapping.如果必须使用@COnfiguration完成 - 我可以同时使用@COnfiguration和servlet-context.xml吗?任何帮助将不胜感激,因为我已经尝试了很长时间.

<context-param>
    <param-name>contextClass</param-name>
    <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>

<context-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>com.test.config</param-value>
</context-param>
Run Code Online (Sandbox Code Playgroud)

configuration spring-mvc spring-annotations spring-3

5
推荐指数
1
解决办法
6472
查看次数

基本测试类中的@Value注释不从属性文件中注入值

出于某种原因,@Value注释不会被注入到我的课程中,而是用作其他测试类的基础.我是Spring的新手,我对Java的了解还不是最好的.我相信对于有更多经验的人来说这会更加明显,但我无法弄清楚这一点.

如果我注释掉该setDbProperties()方法,则会填充字段,但@Value仅使用注释,我会在字段中获得空值.

这是我的基础测试类:

package com.blah;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import org.dbunit.DBTestCase;
import org.dbunit.PropertiesBasedJdbcDatabaseTester;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSetBuilder;
import org.dbunit.operation.DatabaseOperation;
import org.junit.After;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
        "classpath:/WEB-INF/application-context.xml",
        "classpath:/WEB-INF/application-context-test.xml" })
@ActiveProfiles("test")
public abstract class BaseDbTestCase extends DBTestCase {

    @Value("${test.db.connection.url}")
    private String connectionUrl;

    @Value("${test.db.driver.class}")
    private String driverClass;

    @Value("${test.db.username}")
    private String dbUserName;

    @Value("${test.db.password}")
    private String dbPassword;

    @Value("${test.db.datasource.path}")
    private String dataSource;

    public BaseDbTestCase(String …
Run Code Online (Sandbox Code Playgroud)

java spring spring-annotations

5
推荐指数
1
解决办法
3014
查看次数

Spring数据和neo4j的正确注释配置是什么

我正在尝试使用Neo4j配置一个@configuration类的Spring数据,但我找不到任何关于如何正确执行此操作的参考资料,而且我在下一个问题后遇到了一个问题.以下是我到目前为止拼凑的内容:

package reservation.configuration;

import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.kernel.EmbeddedGraphDatabase;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.neo4j.config.EnableNeo4jRepositories;
import org.springframework.data.neo4j.repository.GraphRepositoryFactory;
import org.springframework.data.neo4j.support.Neo4jTemplate;
import org.springframework.data.neo4j.support.mapping.Neo4jMappingContext;

@Configuration
@EnableNeo4jRepositories("reservation.repository.neo4j")
public class Neo4jConfig {

    private static final String STORE_ID = "helloworld";

    @Bean
    public GraphDatabaseService graphDatabaseService() {
        return new EmbeddedGraphDatabase(STORE_ID);
    }

    @Bean
    public Neo4jTemplate neo4jTemplate() {
        return new Neo4jTemplate(graphDatabaseService());
    }

    @Bean
    public GraphRepositoryFactory graphRepositoryFactory() {
        return new GraphRepositoryFactory(neo4jTemplate(), neo4jMappingContext());
    }

    @Bean
    public Neo4jMappingContext neo4jMappingContext() {
        return new Neo4jMappingContext();
    }
}
Run Code Online (Sandbox Code Playgroud)

启动应用程序时的例外情况如下.有什么建议?

java.lang.IllegalStateException: No persistence exception translators found in …
Run Code Online (Sandbox Code Playgroud)

spring-annotations spring-data-neo4j

5
推荐指数
1
解决办法
2890
查看次数

如何以一种方法而不是另一种方法正确注入Spring Environment?

neo4jDatabase()很好,但是environmentgraphDatabaseService()...中为什么总是为空?

@Configuration
@PropertySource("classpath:/neo4j.properties")
@EnableNeo4jRepositories("reservation.repository.neo4j")
public class Neo4jConfig extends Neo4jConfiguration {

    @Inject
    Environment environment;

    @Bean(initMethod = "setupDb")
    public Neo4jDatabase neo4jDatabase() {
        // Environment fine here...
        return new Neo4jDatabase(this.environment.getProperty("data.file.path"));
    }

    @Bean(destroyMethod = "shutdown")
    public GraphDatabaseService graphDatabaseService() {
        if (environment == null) {
            // Always gets here for some reason...why?
            return new EmbeddedGraphDatabase("/Temp/neo4j/database");
        } else {
            return new EmbeddedGraphDatabase(this.environment.getProperty("database.path"));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

版本:Spring 3.2.0.RELEASE,spring-data-neo4j 2.1.0.RELEASE。

spring spring-annotations spring-data-neo4j

5
推荐指数
1
解决办法
7920
查看次数

反正有没有在spring4中禁用注释?

我有一个问题,也许很简单,但我找不到解决方案.

我正在使用spring boot并在代码中添加了一些注释,如下所示:

@EnableEurekaClient
@SpringBootApplication
@EnableCaching
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是在其他一些环境中,例如,在生产环境中,我们想要删除EurekaClient,但我不想手动为每个环境手动删除它,相反,我想使用环境变量或命令行参数来控制行为.我想这样做:

@EnableEurekaClient(Enabled = {EnableEureka})
@SpringBootApplication
@EnableCaching
public class MyApplication {
        public static void main(String[] args) {
            SpringApplication.run(MyApplication.class, args);
        }
}
Run Code Online (Sandbox Code Playgroud)

然后我可以轻松启动此应用程序而无需触及代码.

任何人都可以告诉我这是否可能?如果是这样,我该怎么办?

谢谢

java spring spring-annotations spring-boot spring-cloud

5
推荐指数
1
解决办法
1815
查看次数

Spring框架@Configurable vs @Configuration

我似乎在理解这2个注释时遇到问题。我已经尝试阅读javadocs,但仍然无法弄清楚。谁能用简单的代码来帮助解释这两个问题?提前非常感谢。

spring spring-annotations

5
推荐指数
1
解决办法
5588
查看次数