小编Pat*_*ick的帖子

Spring Batch - 如何使用 jobLauncherTestUtils 防止数据库提交

我有写入数据库的 Spring Batch 作业(它有一个带有 的步骤JpaItemWriter)。我有一个集成测试,如下所示:

@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("integrationTest")
public class LoadApplicationTests {

    @Autowired
    private Job job;

    @Autowired
    private JobRepository jobRepository;

    @Autowired
    private JobLauncher jobLauncher;

    private JobLauncherTestUtils jobLauncherTestUtils;

    @Before
    public void setUp() throws IOException, java.text.ParseException, Exception {       
        jobLauncherTestUtils = new JobLauncherTestUtils();
        jobLauncherTestUtils.setJob(job);
        jobRepository = new MapJobRepositoryFactoryBean(new ResourcelessTransactionManager()).getObject();
        jobLauncherTestUtils.setJobRepository(jobRepository);
        jobLauncherTestUtils.setJobLauncher(jobLauncher);
    }

    @Test
    public void testJob() throws Exception {
        JobParametersBuilder j = new JobParametersBuilder();
        JobParameters jobParameters = j.addDate("runDate", new Date())
                .addString("file", testFile.getAbsolutePath())
                .addString("override", "false")
                .addString("weekly", "false")
                .toJobParameters();

        JobExecution jobExecution = jobLauncherTestUtils.launchJob(jobParameters); …
Run Code Online (Sandbox Code Playgroud)

spring spring-test spring-batch spring-data-jpa spring-boot

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

使用JMH对Spring启动应用程序进行基准测试

我有一个spring boot我想要使​​用的基准测试应用程序JMH.任何有关此集成的参考都将非常有用.

spring-boot jmh

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

从Java 8函数创建请求范围的Bean

基于此答案,我尝试使用java.util.Function接口配置请求范围Bean 。

我的配置如下所示:

@Configuration
public class RequestConfig {

    @Bean
    public Function<? extends BaseRequest, RequestWrapper<? extends BaseRequest, ? extends BaseResponse>> requestWrapperFactory() {
        return request -> requestWrapper(request);
    }

    @Bean
    @RequestScope
    public RequestWrapper<? extends BaseRequest, ? extends BaseResponse> requestWrapper(
            BaseRequest request) {
        RequestWrapper<?, ?> requestWrapper = new RequestWrapper<BaseRequest, BaseResponse>(request);
        return requestWrapper;
    }
}
Run Code Online (Sandbox Code Playgroud)

我尝试像这样使用bean:

@RestController
public class CheckRequestController {

    private final RequestService<CheckRequest, CheckResponse> checkRequestServiceImpl;

    @Autowired
    private Function<CheckRequest, RequestWrapper<CheckRequest, CheckResponse>> requestWrapperFactory;

    public CheckRequestController(
            RequestService<CheckRequest, CheckResponse> checkRequestServiceImpl) {
        super();
        this.checkRequestServiceImpl = …
Run Code Online (Sandbox Code Playgroud)

java spring dependency-injection spring-bean spring-boot

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

获取HTTP状态400 - 必需的MultipartFile参数'file'在spring中不存在

我正在尝试使用上传文件spring.下面是我的代码我是如何工作的,但如果我尝试使用它,我得到这个response:

HTTP状态400 - 不存在所需的MultipartFile参数"file"

我不知道错误是什么.

我正在使用高级休息客户端进行测试,我将文件作为附件上传.

我的Javacode:

@RequestMapping(value = "/upload",headers = "Content-Type=multipart/form-data", method = RequestMethod.POST)
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file)
    {
        String name= "test.xlsx";
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                BufferedOutputStream stream =
                        new BufferedOutputStream(new FileOutputStream(new File(name)));
                stream.write(bytes);
                stream.close();
                return "You successfully uploaded " + name + "!";
            } catch (Exception e) {
                return "You failed to upload " + name + " => " + e.getMessage();
            }
        } else {
            return …
Run Code Online (Sandbox Code Playgroud)

java spring file-upload

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

Spring Redis排序键

我在Redis(Spring Data Redis)中有以下键,

localhost>Keys *
"1+ { \"_id":"1", \"Name\" : \"C5796\" , \"Site\" : \"DRG1\"}"
"2+ { \"_id":"2", \"Name\" : \"CX1XE\" , \"Site\" : \"DG1\"}"
"3+ { \"_id":"3", \"Name\" : \"C553\" , \"Site\" : \"DG1\"}"
Run Code Online (Sandbox Code Playgroud)

如果我想根据id/name/site进行排序,我该怎么办呢Spring Redis

List<Object> keys = redistemplate.sort(SortQueryBuilder.sort("Customer").build());
Run Code Online (Sandbox Code Playgroud)

和,

SortQuery<String> sort = SortQueryBuilder.sort(key).noSort().get(field).build(); 
List<?> keys = redistemplate.boundHashOps(key).getOperations().sort(sort);
Run Code Online (Sandbox Code Playgroud)

不工作.

sorting spring key redis

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

如何在不同主机上使用eureka-server注册eureka-clients.春季启动

我在我的localhost上运行我的eureka-server.我可以在localhost运行服务上注册我所有的其他服务,并且可以像预期的那样注册.

现在我想注册一个在linux机器上运行的服务.我的属性看起来像这样:

spring.application.name=myService-service
spring.cloud.config.uri=http://myMachine.domain.lan:8888
server.port=8002
eureka.client.service-url.default-zone=http://myMachine.domain.lan:8761/eureka/
Run Code Online (Sandbox Code Playgroud)

但该服务无法在localhost上的eureka服务器上注册.(最后它在localhost上运行相同的服务)

我得到了这些例外:

java.net.ConnectException: Connection refused
com.netflix.discovery.shared.transport.TransportException: Cannot execute request on any known server
Run Code Online (Sandbox Code Playgroud)

但是我能够从我在localhost上运行的配置服务中获取配置文件.

从linux机器(客户端)向localhost(服务器)注册我的服务到eureka需要哪些配置?

我使用这个注释:

服务:

@SpringBootApplication
@EnableDiscoveryClient
@EnableEurekaClient
public class MyServiceApplication {
Run Code Online (Sandbox Code Playgroud)

尤里卡服务器:

@SpringBootApplication
@EnableEurekaServer
public class EurekaServiceApplication {
Run Code Online (Sandbox Code Playgroud)

PS:对面方式也不起作用.意味着在linux机器上有eureka服务器,在localhost上有服务.得到相同的例外.

EDIT1:

Eureka-Server属性:

spring.application.name=eureka-service
spring.cloud.config.uri=http://myMachine.domain.lan:8888
server.port=8761
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.instance.hostname=KBHWS242.myDomain.lan
eureka.instance.prefer-ip-address=true
Run Code Online (Sandbox Code Playgroud)

EDIT2:

testsrv是linux机器.(172.25.82.108)

2016-08-31 09:17:01.912  INFO 27105 --- [           main] com.netflix.discovery.DiscoveryClient    : Starting heartbeat executor: renew interval is: 30
2016-08-31 09:17:01.919  INFO 27105 --- [           main] c.n.discovery.InstanceInfoReplicator     : InstanceInfoReplicator onDemand update allowed rate per …
Run Code Online (Sandbox Code Playgroud)

java spring spring-boot netflix-eureka

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

Spring Security HttpSecurity 配置

我尝试了解 RequestMatcher、AntMatcher 等是如何工作的。我阅读了一些帖子并了解了基础知识。实际上我有这个简单的基本配置:

\n\n
@Override\nprotected void configure(HttpSecurity http) throws Exception {\n    http.requestMatchers() //1\n        .antMatchers("/login", "/oauth/authorize") //2\n        .and() //3\n        .authorizeRequests() //4\n        .anyRequest() //5\n        .authenticated() //6;\n
Run Code Online (Sandbox Code Playgroud)\n\n

我真的不明白第 1,2 和 3 点。根据我的理解,这意味着/login和的请求/oauth/authorize请求被映射并且应该是授权请求。所有其他请求都需要进行身份验证。

\n\n

对于端点来说,/user/me我必须进行身份验证,因为它由第 5 点和第 6 点规定?\n对此端点的调用对我有用。

\n\n

在我的其他配置中,我尝试了一种不同的方法:

\n\n
@Override\nprotected void configure(HttpSecurity http) throws Exception { // @formatter:off\n      http\n       .authorizeRequests() //1\n        .antMatchers("/login", "/oauth/authorize", "/img/**").permitAll() //2\n        .anyRequest() //3\n        .authenticated() //4\n
Run Code Online (Sandbox Code Playgroud)\n\n

从我的角度来看,这应该与第一个配置的逻辑相同。但实际上端点/user/me不再可访问。

\n\n

我非常感谢您的澄清

\n\n
\n\n

更新1:

\n\n

这是我现在的配置:

\n\n
@Override\nprotected void configure(HttpSecurity …
Run Code Online (Sandbox Code Playgroud)

java spring spring-security spring-boot spring-oauth2

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

Spring Data:JPA存储库findAll()返回*Map而不是List?

我有一个Spring Data JPA存储库接口,如下所示:

@Repository
public interface DBReportRepository extends JpaRepository<TransactionModel, Long> {

    List<TransactionModel> findAll();
    List<TransactionModel> findByClientId(Long id);
}
Run Code Online (Sandbox Code Playgroud)

有没有一种解决方法可以使相同但是要返回类型的集合HashMap<K, V>?我查看了Spring Data类,除了List <>返回值之外找不到任何其他内容.

java spring-data spring-data-jpa spring-boot

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

Spring-data-elasticsearch @CompletionField 不会创建类型为“完整”的字段

我正在使用Spring-data-elasticsearch并且有ElasticsearchTemplate功能。

我尝试通过@CompletionFieldCompletion名为的字段上使用注释来创建索引suggest

@Document(indexName = "city", type = "city")
public class City {

    @Id
    private String id;

    @Field
    private String name;

    @CompletionField
    private Completion suggest;
}
Run Code Online (Sandbox Code Playgroud)

@CompletionField注释应被用来为elasticsearch的建议,功能齐全。就像在 java-doc 中描述的那样:

/**
 * Based on the reference doc - http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-suggesters-completion.html
 *
 * @author Mewes Kochheim
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Documented
@Inherited
public @interface CompletionField {
Run Code Online (Sandbox Code Playgroud)

在他们说的elasticsearch 文档中,该字段应该有一个类型complete来使用建议完成功能。

但是,如果我不幸地创建索引,该字段suggest没有 typecomplete而是它具有 type keyword。当我尝试查询建议查询时,这给了我一个错误。

CompletionSuggestionBuilder s …
Run Code Online (Sandbox Code Playgroud)

java elasticsearch spring-boot spring-data-elasticsearch

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

如何在spring boot中添加基于条件的@NotNull约束?

我们正在使用spring-boot. 我想在 java 类中添加基于条件的约束。例如

@Entity
public class User {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name = "user_id")
    private Integer userId;
    @Column(name = "firstName")
    private String firstName;
    @Column(name = "lastName")
    private String lastName;
}
Run Code Online (Sandbox Code Playgroud)

现在在上面的代码中@NotNulllastName当且仅当firstName属性不为空时,我想对属性施加约束。

annotations spring-boot

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