小编Pat*_*ick的帖子

Java 8 LocalDate - 如何获取两个日期之间的所有日期?

是否可以在新java.timeAPI中获取两个日期之间的所有日期

假设我有这部分代码:

@Test
public void testGenerateChartCalendarData() {
    LocalDate startDate = LocalDate.now();

    LocalDate endDate = startDate.plusMonths(1);
    endDate = endDate.withDayOfMonth(endDate.lengthOfMonth());
}
Run Code Online (Sandbox Code Playgroud)

现在我需要startDate和之间的所有日期endDate.

我想要得到daysBetween两个日期并迭代:

long daysBetween = ChronoUnit.DAYS.between(startDate, endDate);

for(int i = 0; i <= daysBetween; i++){
    startDate.plusDays(i); //...do the stuff with the new date...
}
Run Code Online (Sandbox Code Playgroud)

有更好的方法来获取日期吗?

java date java-8 java-time

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

如何测试Spring-boot应用程序的主类

我有一个spring-boot应用程序,我的@SpringBootApplication入门级看起来像一个标准的.所以我为我的所有功能创建了许多测试,并将摘要发送给sonarqube以查看我的报道.

对于我的初级班,Sonarqube告诉我,我只有60%的覆盖率.因此平均覆盖率不如预期.

在此输入图像描述

我的Test类只是默认类.

@RunWith(SpringRunner.class)
@SpringBootTest(classes = ElectronicGiftcardServiceApplication.class)
public class ElectronicGiftcardServiceApplicationTests {

    @Test
    public void contextLoads() {
    }
}
Run Code Online (Sandbox Code Playgroud)

那么如何在我的应用程序的入门类中测试我的主类?

java junit spring-boot

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

如何以优雅的方式初始化具有大量字段的类?

在我的应用程序中,我必须实例化许多不同类型的对象.每种类型都包含一些字段,需要添加到包含类型中.我怎样才能以优雅的方式做到这一点?

我当前的初始化步骤看起来像这样:

public void testRequest() {

        //All these below used classes are generated classes from xsd schema file.

        CheckRequest checkRequest = new CheckRequest();

        Offers offers = new Offers();
        Offer offer = new Offer();
        HotelOnly hotelOnly = new HotelOnly();
        Hotel hotel = new Hotel();
        Hotels hotels = new Hotels();
        Touroperator touroperator = new Touroperator();
        Provider provider = new Provider();
        Rooms rooms = new Rooms();
        Room room = new Room();
        PersonAssignments personAssignments = new PersonAssignments();
        PersonAssignment personAssignment = new PersonAssignment(); 
        Persons persons …
Run Code Online (Sandbox Code Playgroud)

java coding-style builder code-cleanup object-construction

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

Spring-Boot中的application.properties属性的UTF-8编码

在我的application.properties添加一些自定义属性.

custom.mail.property.subject-message=This is a ä ö ü ß problem
Run Code Online (Sandbox Code Playgroud)

在这个类中,我有自定义属性的表示.

@Component
@ConfigurationProperties(prefix="custom.mail.property")
public class MailProperties {
    private String subjectMessage;
    public String getSubjectMessage() {
        return subjectMessage;
    }
    public void setSubjectMessage(String subjectMessage) {
        this.subjectMessage = subjectMessage;
    }
Run Code Online (Sandbox Code Playgroud)

在这里我用我的MailProperties:

@Service
public class SimpleUnknownResponseMessage extends MailProperties implements UnknownResponseMessage{

    private JavaMailSender javaMailSender;

    @Autowired
    public SimpleUnknownResponseMessage(JavaMailSender javaMailSender) {
        this.javaMailSender = javaMailSender;
    }

    @Override
    public void placeUnknownResponse(BookResponse bookResponse) {
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, "UTF-8");
            helper.setSubject(this.getSubjectMessage());            
            javaMailSender.send(message); …
Run Code Online (Sandbox Code Playgroud)

java encoding spring utf-8 spring-boot

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

无法构造`java.time.LocalDate`的实例 - Spring boot,elasticseach,jackson

我正在使用Spring-boot 2.0.0.M7and spring-boot-starter-data-elasticsearchelasticsearch 5我通过反序列化LocalDate字段得到错误.

我的文档看起来像这样:

@Document(indexName= "myIndex", type = "cluster")
public class Cluster {

    @Id
    @Field
    private Long id;
    @Field
    private String name;
    @Field
    private ClusterUrl clusterUrl;
    @Field
    private ClusterVisible clusterVisible;
}
Run Code Online (Sandbox Code Playgroud)

其中ClusterVisible是一个子对象,它包含LocalDates:

public class ClusterVisible {

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd.MM.yyyy")
    private LocalDate start;
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd.MM.yyyy")
    private LocalDate end;
}
Run Code Online (Sandbox Code Playgroud)

所以我只是查询一个集群ID,我得到了这个异常:

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `java.time.LocalDate` (no Creators, like default construct, exist): cannot deserialize …
Run Code Online (Sandbox Code Playgroud)

java spring jackson elasticsearch spring-boot

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

具有多个SELECT NEW语句的jpa构造函数表达式

有没有办法SELECT NEWjpql查询中使用多个语句(Hibernate)?

这对我有用:

@Query("SELECT NEW com.test.project.dto.ItemService(g,s,l,r) "
        +" FROM Item g, Service s, Service l , Service r"
        +" WHERE s.id = g.id" 
        +" AND s.location = l.name"
        +" AND s.serviceType = 'type'"
        +" AND l.serviceType = 'Location'"
        +" AND l.area = r.name" 
        +" AND r.serviceType = 'Region'")
public List<Item> getAllItemsWithServices();
Run Code Online (Sandbox Code Playgroud)

我得到了预期的结果DTO.

@Component
public class ItemServiceDTO{

    private Item item;
    private Service serviceType;
    private Service serviceLocation;
    private Service serviceRegion;

    public ItemServiceDTO(item item, Service serviceType, Service …
Run Code Online (Sandbox Code Playgroud)

java spring hibernate jpa jpql

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

在Junit测试中使用ReflectionTestUtils.setField()

我是JUnittesting的新手,所以我有一个问题.任何人都可以告诉我为什么我们ReflectionTestUtils.setField()在我们的Junit测试中使用示例.

java junit spring

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

Spring boot在@SpringBootApplication类上找不到默认构造函数

我想知道为什么字段注入在@SpringBootApplication类中工作而构造函数注入没有.

ApplicationTypeBean正在按预期工作,但是当我想要构造函数注入时,CustomTypeService我收到此异常:

Failed to instantiate [at.eurotours.ThirdPartyGlobalAndCustomTypesApplication$$EnhancerBySpringCGLIB$$2a56ce70]: No default constructor found; nested exception is java.lang.NoSuchMethodException: at.eurotours.ThirdPartyGlobalAndCustomTypesApplication$$EnhancerBySpringCGLIB$$2a56ce70.<init>()
Run Code Online (Sandbox Code Playgroud)

有什么理由不在@SpringBootApplication课堂上工作吗?


我的SpringBootApplication类:

@SpringBootApplication
public class ThirdPartyGlobalAndCustomTypesApplication implements CommandLineRunner{

@Autowired
ApplicationTypeBean applicationTypeBean;

private final CustomTypeService customTypeService;

@Autowired
public ThirdPartyGlobalAndCustomTypesApplication(CustomTypeService customTypeService) {
    this.customTypeService = customTypeService;
}

@Override
public void run(String... args) throws Exception {
    System.out.println(applicationTypeBean.getType());
    customTypeService.process();
}

public static void main(String[] args) {
    SpringApplication.run(ThirdPartyGlobalAndCustomTypesApplication.class, args);
}

public CustomTypeService getCustomTypeService() {
    return customTypeService;
}
Run Code Online (Sandbox Code Playgroud)

我的@Service类:

@Service
public class CustomTypeService { …
Run Code Online (Sandbox Code Playgroud)

java spring spring-boot

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

SerializationFeature.WRAP_ROOT_VALUE作为jackson json中的注释

有没有办法SerializationFeature.WRAP_ROOT_VALUE在根元素上配置注释而不是使用ObjectMapper

例如,我有:

@JsonRootName(value = "user")
public class UserWithRoot {
    public int id;
    public String name;
}
Run Code Online (Sandbox Code Playgroud)

使用ObjectMapper:

@Test
public void whenSerializingUsingJsonRootName_thenCorrect()
  throws JsonProcessingException {
    UserWithRoot user = new User(1, "John");

    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
    String result = mapper.writeValueAsString(user);

    assertThat(result, containsString("John"));
    assertThat(result, containsString("user"));
}
Run Code Online (Sandbox Code Playgroud)

结果:

{
    "user":{
        "id":1,
        "name":"John"
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法将此SerializationFeature作为注释而不是作为配置objectMapper

使用依赖:

<dependency>
     <groupId>com.fasterxml.jackson.core</groupId>
     <artifactId>jackson-databind</artifactId>
     <version>2.7.2</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

java serialization json jackson

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

使用来自 yaml 文件的多个 cron 表达式 Spring-Boot 一个 @Scheduled 任务

我喜欢@Scheduled使用.yml文件的不同配置属性来实现一项作业。

在我的 yaml 文件中,我将其描述cron expression为列表:

job:
  schedules:
  - 10 * * * * *
  - 20 * * * * *
Run Code Online (Sandbox Code Playgroud)

我使用 Configuration 读出这些值并创建了一个@Bean命名的scheduled

@Configuration
@ConfigurationProperties(prefix="job", locations = "classpath:cronjob.yml")
public class CronConfig {

    private List<String> schedules;

    @Bean
    public List<String> schedules() {
        return this.schedules;
    }

    public List<String> getSchedules() {
        return schedules;
    }

    public void setSchedules(List<String> schedules) {
        this.schedules = schedules;
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的 Job 类中,我想开始执行一种方法,但是对于我的配置中的两个计划。

 @Scheduled(cron = "#{@schedules}")
 public String execute() …
Run Code Online (Sandbox Code Playgroud)

java cron spring spring-boot

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