小编les*_*nar的帖子

Spring boot 1.4测试:配置错误:找到了@BootstrapWith的多个声明

按照官方文档:http: //docs.spring.io/spring-boot/docs/1.4.0.M2/reference/htmlsingle/#Testing

我想测试一个我的REST API方法,如下所示:

@RunWith(SpringRunner.class)
@WebMvcTest(LoginController.class)
@SpringBootTest(classes = Application.class)
public class AuthorizationServiceTest {
    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    public void test() {
        Object returnedObject=his.restTemplate.getForObject("/login", Object.class);
    }
}
Run Code Online (Sandbox Code Playgroud)

正如文件中所述:

搜索算法从包含测试的包开始工作,直到找到@SpringBootApplication或@SpringBootConfiguration注释类.只要您以合理的方式构建代码,通常就会找到主要配置.

我已正确构建了我的代码(至少我认为):

AuthorizationService:在包com.xxx.yyy.zzz.authorization下;

AuthorizationServiceTest:在包com.xxx.yyy.zzz.authorizationTest下;

我收到此异常(完整跟踪):

java.lang.IllegalStateException: Configuration error: found multiple declarations of @BootstrapWith for test class [com.orangeraid.rasberry.gateway.authorizationTest.AuthorizationServiceTest]: [@org.springframework.test.context.BootstrapWith(value=class org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTestContextBootstrapper), @org.springframework.test.context.BootstrapWith(value=class org.springframework.boot.test.context.SpringBootTestContextBootstrapper)]
    at org.springframework.test.context.BootstrapUtils.resolveExplicitTestContextBootstrapper(BootstrapUtils.java:155)
    at org.springframework.test.context.BootstrapUtils.resolveTestContextBootstrapper(BootstrapUtils.java:126)
    at org.springframework.test.context.TestContextManager.<init>(TestContextManager.java:105)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTestContextManager(SpringJUnit4ClassRunner.java:152)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.<init>(SpringJUnit4ClassRunner.java:143)
    at org.springframework.test.context.junit4.SpringRunner.<init>(SpringRunner.java:49)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
    at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
    at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59) …
Run Code Online (Sandbox Code Playgroud)

java spring spring-mvc spring-test spring-boot

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

Spring mvc:将默认的响应格式从xml更改为json

我已经解决了其他类似问题,但对我来说没有任何效果.

默认情况下,所有API都将JSON作为响应返回:

由于一些XML API,我不得不添加jackson-xml

    <dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    </dependency>
Run Code Online (Sandbox Code Playgroud)

现在默认情况下" 没有接受标头"所有响应都是XML.

我想将JSON作为默认的响应格式.

正如文档中所述:

https://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc

我实现了以下配置:

@Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.favorPathExtension(false).favorParameter(true).parameterName("mediaType").ignoreAcceptHeader(true)    
                .useJaf(false).defaultContentType(MediaType.APPLICATION_JSON)
                .mediaType("xml", MediaType.APPLICATION_XML).mediaType("json", MediaType.APPLICATION_JSON);
    }
Run Code Online (Sandbox Code Playgroud)

案例1:如果我做了,ignoreAcceptHeader(true) 那么即使是返回JSON的XML API,一切都是JSON.

情况2:何时ignoreAcceptHeader(false)是默认值是XML.

我忘了提到我的API看起来像这样:

@RequestMapping(value = "/getXml", method = RequestMethod.GET)
public ResponseEntity<String> getXml( HttpServletRequest request)
        throws JAXBException {
    return returnXml();
}
Run Code Online (Sandbox Code Playgroud)

我在这里很丢失,我想要的只是默认(没有AcceptHeader)应该是JSON.(API将XML作为String返回)

当Accept Header:"Application/xml"被定义时,响应应该是XML.

任何建议都会有很大的帮助.

谢谢.

spring spring-mvc spring-boot

11
推荐指数
2
解决办法
5116
查看次数

NoUniqueBeanDefinitionException:没有定义[javax.persistence.EntityManagerFactory]类型的限定bean:期望的单个匹配bean

我有2个独立的数据库,我试图在存储库中访问它们.不幸的是,我收到以下异常.

我尝试过的事情

  • 尝试将其中一个bean作为Primary.
  • 使用了PersistenceContext,如下面的代码所示.

我的ExceptionTrace

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'orderController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.crud.repository.mymerkNew.OrderRepository com.crud.controller.OrderController.nextGenorder; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'orderRepository': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined: expected single matching bean but found 2: mymerkLimsEntityManagerFactory,nextGenEntityManagerFactory
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1202)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at …
Run Code Online (Sandbox Code Playgroud)

spring spring-mvc spring-orm spring-boot beancreationexception

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

如何使用用户定义的偏移量和限制(范围)通过Spring数据JPA查询数据

是否可以获取用户定义范围内的数据[int starting record -int last record]?

在我的情况下,用户将在查询字符串中定义他想要获取数据的范围.我尝试过这样的事情

Pageable pageable = new PageRequest(0, 10);
    Page<Project> list = projectRepository.findAll(spec, pageable);
Run Code Online (Sandbox Code Playgroud)

spec是我定义的规范,但不幸的是,这没有帮助.可能是我在这里做错了.

我见过其他spring jpa提供的方法,但没有什么帮助.

用户可以输入类似localhost:8080/Section/employee的内容吗?范围{ "COLUMNNAME":名称 "从":6, "到":20}

所以这表示获取员工数据并且它将获取前15条记录(按columnName排序)并不重要.

如果你能给我一些更好的建议,如果你认为我没有提供足够的信息请告诉我,我会提供所需的信息.

更新:我不想使用本机或创建查询语句(直到我没有任何其他选项).可能是这样的:

Pageable pageable = new PageRequest(0, 10);
        Page<Project> list = projectRepository.findAll(spec, new pageable(int startIndex,int endIndex){
// here my logic.

});
Run Code Online (Sandbox Code Playgroud)

如果你有更好的选择,你也可以建议我.

谢谢.

spring spring-mvc spring-data spring-data-jpa

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

css用于不同的屏幕分辨率?

如果我在具有不同分辨率的2个不同系统上检查html,则视图会失真.

有没有办法在运行时计算屏幕宽度和高度?

我缺乏css的经验,但做了一些研究,发现:

https://css-tricks.com/css-media-queries/

但他们建议不同的课程.(如果我没错)

我的问题是可以在运行时获得高度和宽度,并只使用一个CSS?

就像是 :

.view {
min-width :"some how gets computed:which device we are using ?"
min-height :"some how gets computed:which device we are using ?"
}
Run Code Online (Sandbox Code Playgroud)

html css media-queries

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

如何使方法接受包含任何数据类型的对象的List

我的目标是检查类型,messages然后相应地将它们转换为字符串并添加它们.我怎样才能做到这一点?

public void addMessages(List<?> messages) {
    if (messages != null) {
        if (messages instanceof String) {
            for (String message : messages) {
                this.messages.add(message);
            }
        }
    }

    else {
        for (Object message:messages) {
            this.messages.add(String.valueOf(message));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

java

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

Logback-布局模式中的自定义级别输入

我正在使用logback进行日志记录,并且在logback.xml中我将控制台附加程序作为

<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>

              <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
            </encoder>
    </appender>.
Run Code Online (Sandbox Code Playgroud)

我正在努力实现这样的目标...

time  thread  |-**CUSTOMLOGLEVEL**  xyz.class - Message.
Run Code Online (Sandbox Code Playgroud)

为什么呢 我想通过定义日志级别或其他某种指标来轻松过滤消息。

例如:搜索日志级别为“ CUSTOMLOGLEVEL”的日志。有没有办法提供自定义日志级别或任何其他指示符,它表明这是自定义生成的日志,而不是某些框架生成的日志。

我进入了创建自定义类的方向。

<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
         <encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
            <layout class="com.logging.CustomLayout">
                             <param name="argument1" value="1" />
                             <param name="argument2" value="2" />

            </layout>
        </encoder>
    </appender>
Run Code Online (Sandbox Code Playgroud)

但我不确定如何将外部输入这些参数。

如果我不清楚,请告诉我。

java logging logback appender

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

不调用Spring REST API控制器

我有以下代码

调节器

@RestController 
@RequestMapping("/") 
public class RequestHandler {
    @RequestMapping(value = "/demo", method = RequestMethod.POST)
     @ResponseBody 
    public Object showDemo() {

        return "Post method";
    }


    @RequestMapping(value = { "/getdemo" }, method = RequestMethod.GET)
      @ResponseBody 
    public  Object showgetDemo() {
  System.out.println("hello");
        return "get Method";
    }
}
Run Code Online (Sandbox Code Playgroud)

我的pom xml

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>Website2015</groupId>
  <artifactId>Website2015</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.2.1.RELEASE</version>
        <relativePath />
    </parent>
    <dependencies>
<dependency> 
<groupId>org.springframework.boot</groupId> 
<artifactId>spring-boot-starter-web</artifactId> 
</dependency> 

<dependency> 
<groupId>org.springframework.boot</groupId> 
<artifactId>spring-boot-starter-test</artifactId> 
<scope>test</scope> 
</dependency> 
</dependencies>  
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.3</version>
        <configuration>
          <source>1.8</source> …
Run Code Online (Sandbox Code Playgroud)

java spring spring-mvc spring-boot

4
推荐指数
1
解决办法
4866
查看次数

如何使用spring security(spring boot)实现Ldap身份验证

我有以下代码与我我试图实现ldap身份验证,但我认为它没有发生.

我的安全配置

@EnableWebSecurity
@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class Config extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.httpBasic().and().authorizeRequests().antMatchers("/*")
                .permitAll().anyRequest().authenticated().and().csrf()
                .disable().httpBasic().and().csrf()
                .csrfTokenRepository(csrfTokenRepository()).and()
                .addFilterAfter(csrfHeaderFilter(), CsrfFilter.class);

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
            throws Exception {
        auth.ldapAuthentication()
                .userSearchFilter("(uid={0})")
                .userSearchBase("dc=intern,dc=xyz,dc=com")
                .contextSource()
                .url("ldap://192.168.11.11:1234/dc=intern,dc=xyz,dc=com")
                .managerDn("username")
                .managerPassword("password!")
                .and()
                .groupSearchFilter("(&(objectClass=user)(sAMAccountName=" + "username" + "))");

    }

    private Filter csrfHeaderFilter() {
        return new OncePerRequestFilter() {
            @Override
            protected void doFilterInternal(HttpServletRequest request,
                    HttpServletResponse response, FilterChain filterChain)
                    throws ServletException, IOException {
                CsrfToken csrf = (CsrfToken) request
                        .getAttribute(CsrfToken.class.getName());
                if (csrf != null) { …
Run Code Online (Sandbox Code Playgroud)

java spring spring-mvc spring-security spring-boot

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

模型驱动形式:验证未按预期在Angular 2中运行

我正在使用这样的模型驱动形式。就像常规验证一样,如果用户名和密码丢失,我希望显示一条错误消息。

只要用户名和密码无效,就应该禁用“提交”按钮。

<div class="login">
<form #f="ngForm" (ngSubmit)="dologin(f)">
    <div class="form-group">
        <label for="username">Username</label>
        <input id="username" type="text" class="form-control" name ="username" ngModel #username="ngModel">

        <div [hidden]="username.valid" class="alert alert-danger"> Username is required.</div>
    </div>
    <div class="form-group">
        <label for="password">Password</label>
        <input id="password" type="password" class="form-control" name ="password" ngModel #password="ngModel">
        <div [hidden]="password.valid" class="alert alert-danger"> Password is required.</div>
    </div>

    <button type="submit" [disabled]="username.length<0 || password.length<0" class="btn btn-primary" type="submit">Login</button>
</form>
</div>
Run Code Online (Sandbox Code Playgroud)
  • 我从验证div看到了非常奇怪的行为。有时显示“需要密码”,有时则不显示。
  • 我想禁用提交按钮,直到表单有效。

[disabled] =“!f.valid”

但是当我打印出来时,即使我没有在用户名和密码中输入任何数据,f仍然有效。

零件:

constructor(private router: Router,private authenticationService : AuthenticationService,private httpService:HttpService,private formBuilder:FormBuilder) {
    this.form=formBuilder.group({
        username:['',Validators.required],
        password:['',Validators.required]
    });

}
Run Code Online (Sandbox Code Playgroud)

更新 …

html html5 angular

3
推荐指数
1
解决办法
6638
查看次数

ngSwitch 默认情况不执行

我想在我的代码中实现ngSwitch如下:

<div [ngSwitch]="accessLevel">
    <div class="customer" *ngSwitchCase="ENABLED">
        This is customer data
    </div>
    <div  *ngSwitchDefault> 
        this is default
    </div>
    <div class="customer-blurr" *ngSwitchCase="DISABLED"> 
        This is disabled Customer Data
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

就我而言accessLevel,未定义,我期待this is default但它显示:

This is customer data.

This is disabled Customer Data.
Run Code Online (Sandbox Code Playgroud)

正如我从官方文档中读到的,如果没有任何匹配,它应该进入默认情况。我错过了什么吗?

angular

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

如何使用Streams将一种类型的List转换为另一种类型的List?

我想用Streams来实现以下目的:

我有完整不同结构的列表InputOutput对象.

使用for循环,我可以将a转换List<Input>为a List<Output>,如下所示:

for (Input input : listOfInput) {
    Output currentOutPutInstance = new Output();
    currentOutPutInstance.setArg1(input.getArg2());
    currentOutPutInstance.setArg2(input.getArg7());
    listOfOutPuts.add(currentOutPutInstance);
}
Run Code Online (Sandbox Code Playgroud)

有了溪流,我试过这样的事情:

private List<Output> getOutPutListFromInputList(List<Input> inPutList) {
    List<Output> outPutList = new ArrayList<Output>();
    outPutList = listOfPoolsInRun.stream.filter(<Somehow converting the input into output>)
                                 .collect(Collectors.toList()); 
}
Run Code Online (Sandbox Code Playgroud)

注意: 我不确定Stream我应该使用哪种方法.我filter只是用来显示一些虚拟代码.

java java-8 java-stream

0
推荐指数
1
解决办法
125
查看次数

Curl 请求:使用curl 请求的响应格式不正确(xml)

我正在使用curl从远程将xml加载为字符串,如下所示:

$ curl -i -H "Accept: application/xml"  -X GET "URL Here"
Run Code Online (Sandbox Code Playgroud)

但响应不是 xml 格式,因此不易阅读。

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><RunConfig <PipeLineXmlVersion>1.0</PipeLineXmlVersion><DateTime>20161128_160859</DateTime><Analysis><Lane>1</Lane><PipeLine>run_multiplexed_auto_start_v4.0.sh</PipeLine><Version>4.0</Version><Mismatch>1</Mismatch><MergeLane>0</MergeLane<Version>4.0</Version></Analysis></RunConfig>
Run Code Online (Sandbox Code Playgroud)

当我使用一些 REST 客户端尝试相同的 API 时,我可以看到正确的 xml。

正如我搜索的那样,接受标头应该可以工作,但不幸的是在我的情况下不行。

请在这件事上给予我帮助。

谢谢。

shell command-line curl

0
推荐指数
1
解决办法
6474
查看次数