小编Raj*_*ami的帖子

Maven项目无法建立

当我运行项目时,我得到编译错误.我想我在pom.xml中做错了什么.我试图用spring做一个示例项目,并从spring示例中添加了依赖项.当我选择目标为"干净安装"的maven构建时,我收到错误.我使用Eclipse Luna.

的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>com.rajkishan.learnSpring</groupId>
<artifactId>RestfulWithSpring</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>

<name>LearnRESTfulSpring</name>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.2.3.RELEASE</version>
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
    <!-- Shared version number properties -->
    <org.springframework.version>4.0.4.RELEASE</org.springframework.version>
    <start-class>com.rajkishan.Application</start-class>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- Core utilities used by other modules. Define this if you use Spring 
        Utility APIs (org.springframework.core.*/org.springframework.util.*) -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>

    <!-- Expression Language (depends on spring-core) Define this if you use 
        Spring Expression APIs (org.springframework.expression.*) -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-expression</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>

    <!-- …
Run Code Online (Sandbox Code Playgroud)

spring spring-mvc maven java-8

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

制作多个实体管理器(Spring-Boot-JPA、Hibernate、MSSQL)

我想连接到 2 个不同的数据库(MSSQL)。所以我喜欢下面。虽然我的ProductController作品,没有CustomerController。添加客户控制器后,spring boot 应用程序不会启动,因为它不能@Autowire CustomerDAO

这里有什么问题,我该如何工作?

我所做的如下所示,

应用程序属性

DatabaseIP=myip
DatabasePort=1433
DB1DatabaseName=Test
DB2DatabaseName=Test2
DatabaseUser=sa
DatabasePwd=boomboom
#DB1
datasource.db1.url=jdbc:sqlserver://${DatabaseIP}:${DatabasePort};databaseName=${DB1DatabaseName}
datasource.db1.username=${DatabaseUser}
datasource.db1.password=${DatabasePwd}
datasource.db1.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver

datasource.db2.url=jdbc:sqlserver://${DatabaseIP}:${DatabasePort};databaseName=${DB2DatabaseName}
datasource.db2.username=${DatabaseUser}
datasource.db2.password=${DatabasePwd}
datasource.db2.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver

spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.EJB3NamingStrategy
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.SQLServerDialect

spring.jpa.show-sql=true

security.user.name=raj
security.user.password=raj123456
Run Code Online (Sandbox Code Playgroud)

DB1EntityManager.java

@Configuration
@EnableTransactionManagement
@EnableAutoConfiguration
@EntityScan(basePackages = "com.rajkishan.db1Entities")
@EnableJpaRepositories(transactionManagerRef = "db1TransactionManager", entityManagerFactoryRef = "db1EntityManagerFactory", basePackages = "com.rajkishan.db1DAOs")
public class DB1EntityManager {

@Bean(name = "db1DataSource")
@Primary
@ConfigurationProperties(prefix = "datasource.db1")
public DataSource db1DataSource() {
    return DataSourceBuilder.create().build();
}

@Bean(name = "db1EntityManagerFactory")
@Primary
public LocalContainerEntityManagerFactoryBean db1EntityManagerFactory(final EntityManagerFactoryBuilder builder) …
Run Code Online (Sandbox Code Playgroud)

java sql-server hibernate jpa spring-boot

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

添加动态侦听器数量(Spring JMS)

我需要添加application.properties文件中提到的多个侦听器.像下面一样,

InTopics=Sample.QUT4,Sample.T05,Sample.T01,Sample.JT7
Run Code Online (Sandbox Code Playgroud)

注意:这个数字可以更多或更少.

我想把它们放在一个数组中,

@Value("${InTopics}")
private String[] inTopics;
Run Code Online (Sandbox Code Playgroud)

但我不知道如何从数组创建多个侦听器.

目前,我正在做的一个主题如下,

@Configuration
@EnableJms
public class JmsConfiguration {

@Value("${BrokerURL}")
private String brokerURL;

@Value("${BrokerUserName}")
private String brokerUserName;

@Value("${BrokerPassword}")
private String brokerPassword;

@Bean
TopicConnectionFactory connectionFactory() throws JMSException {
    TopicConnectionFactory connectionFactory = new TopicConnectionFactory(brokerURL, brokerUserName, brokerPassword);
    return connectionFactory;
}

@Bean
JmsListenerContainerFactory<?> jmsContainerFactory(TopicConnectionFactory connectionFactory) throws JMSException {
    SimpleJmsListenerContainerFactory factory = new SimpleJmsListenerContainerFactory();
    factory.setConnectionFactory(connectionFactory);
    factory.setPubSubDomain(Boolean.TRUE);
    return factory;
 }

}
Run Code Online (Sandbox Code Playgroud)

而我的倾听者,

@JmsListener(destination = "${SingleTopicName}", containerFactory = "jmsContainerFactory")
public void receiveMessage(Message msg) {
   //Do Some Stuff
} …
Run Code Online (Sandbox Code Playgroud)

java spring jms spring-jms spring-boot

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

更改Spring应用程序启动消息

我用spring boot来做样品服务.当我在命令行中使用"java -jar DemoLibrary.war"命令运行它时,它工作正常.我得到了"图书馆应用程序已启动"的正确信息.

我在Appplication.java文件中确实如下;

@SpringBootApplication
public class Application extends SpringBootServletInitializer {

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    return application.sources(Application.class);
}

public static void main(String[] args) {
    ApplicationContext context = SpringApplication.run(Application.class, args);
    LogService.info(Application.class.getName(), "Library Application Has Started.");
}
   }
Run Code Online (Sandbox Code Playgroud)

当我在外部tomcat中运行它时,它启动正常并且工作正常.但我不会看到相同的消息,因为它不再使用该主要方法.我只看到spring应用程序启动消息.

有没有办法可以改变那条消息,并按我想要的方式给出?

java spring spring-mvc spring-boot

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

相同的内容但JUnit测试失败(IntelliJ)

我有一个比较两个字符串的JUnit测试:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = CDPlayerConfig.class)
public class CDPlayerTest {

    @Rule
    public final SystemOutRule log = new SystemOutRule().enableLog();

    @Autowired
    private CompactDisc cd;

    @Autowired
    private MediaPlayer player;

    @Test
    public void cdShouldNotBeNull() {
        assertNotNull(cd);
    }

    @Test
    public void play() {
        player.play();
        assertEquals("Playing title Sgt. Pepper's Lonely Hearts Club Band by artist The Beatles\n",
                log.getLog());
    }
}
Run Code Online (Sandbox Code Playgroud)

org.junit.ComparisonFailure在第二次测试时遇到异常.但是,IntelliJ显示的内容是相同的.我错过了什么?

编辑:添加回预期字符串末尾的\n.

在此输入图像描述

java junit intellij-idea system-rules

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

反转GregorianCalender对象的add minute方法

当向GregorianCalender对象添加一分钟时,我们在下面添加1分钟的时间:

GregorianCalendar gc = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
gc.add(Calendar.MINUTE,1);
Run Code Online (Sandbox Code Playgroud)

但是错误地,我把它颠倒了:

GregorianCalendar gc = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
gc.add(1,Calendar.MINUTE);
Run Code Online (Sandbox Code Playgroud)

这增加了12年的时间.任何人都可以描述为什么会这样吗?我对Java的了解并不好,所以我很好奇为什么会这样.

java datetime

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

用不同的值替换长字符串的部分

我有一个像下面的字符串;

String textToShow = "Appplication [%ApplicationName%]: started at [%Date%][%Time%]"

当我需要在替换字符串之间[%%]不同的价值观.

我确实喜欢下面,但它只适用于第一个,即"ApplicationName".

private String getTextVariableName(String stringToShow) {
    if (stringToShow.contains("[%") && stringToShow.contains("%]")) {
        String content[] = notificationText.split("%");
        return content[1];
    }
    return null;
}

private String replaceValue(String stringToShow, String dataToReplace) {
    return stringToShow.substring(0, stringToShow.indexOf("["))
            + dataToReplace
            + stringToShow.substring(stringToShow.indexOf("]") + 1, stringToShow.length());
}

public String processText(String stringToShow, String appname) {
    String variableName = getTextVariableName(stringToShow);
    String processedText = "Invalid";
    if (variableName != null) {
        switch (variableName.toLowerCase()) {

        case "applicationname":
            processedText = …
Run Code Online (Sandbox Code Playgroud)

java string java-8

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

在 Spring Boot 测试中使用 @RestClientTest

我想为@RestClientTest下面的组件编写一个简单的测试(注意:我可以在不使用@RestClientTest和模拟工作正常的依赖 bean 的情况下完成它。)。

@Slf4j
@Component
@RequiredArgsConstructor
public class NotificationSender {

    private final ApplicationSettings settings;
    private final RestTemplate restTemplate;

    public ResponseEntity<String> sendNotification(UserNotification userNotification)
            throws URISyntaxException {
            // Some modifications to request message as required
            return restTemplate.exchange(new RequestEntity<>(userNotification, HttpMethod.POST, new URI(settings.getNotificationUrl())), String.class);
    }
}
Run Code Online (Sandbox Code Playgroud)

和测试;

@RunWith(SpringRunner.class)
@RestClientTest(NotificationSender.class)
@ActiveProfiles("local-test")
public class NotificationSenderTest {

    @MockBean
    private ApplicationSettings settings;
    @Autowired
    private MockRestServiceServer server;
    @Autowired
    private NotificationSender messageSender;

    @Test
    public void testSendNotification() throws Exception {
        String url = "/test/notification";
        UserNotification …
Run Code Online (Sandbox Code Playgroud)

spring-boot spring-rest spring-boot-test

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

来自xsd的maven-jaxb2-plugin类生成(版本错误)

我的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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.rajkishan</groupId>
<artifactId>RESTful-Swagger</artifactId>
<packaging>war</packaging>
<version>1.0.0</version>

<name>RESTful-Swagger</name>

<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>1.2.4.RELEASE</version>
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
    <start-class>com.rajkishan.Application</start-class>
</properties>

 <dependencies>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<dependency>
    <groupId>com.mangofactory</groupId>
    <artifactId>swagger-springmvc</artifactId>
    <version>1.0.2</version>
</dependency>

</dependencies>

 <build>
<plugins>

    <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
    </plugin>

    <plugin>
            <groupId>org.jvnet.jaxb2.maven2</groupId>
            <artifactId>maven-jaxb2-plugin</artifactId>
            <version>0.12.3</version>
            <executions>
                <execution>
                    <goals>
                        <goal>generate</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <schemaDirectory>src/main/resources</schemaDirectory>
                <schemaIncludes>
                    <include>Greeting.xsd</include>
                </schemaIncludes>
                <generatePackage>com.rajkishan.xmlgen</generatePackage>
            </configuration>
        </plugin>

</plugins>
Run Code Online (Sandbox Code Playgroud)

当我在"Netbeans"中使用maven构建时,这很好用.

但是,如果我在Eclipse Luna中使用它,它会给出错误;

目标org.jvnet.jaxb2.maven2的执行默认值:maven-jaxb2-plugin:0.12.3:生成失败:执行org.jvnet.jaxb2.maven2时缺少必需的类:maven-jaxb2-plugin:0.12.3: generate:com/sun/xml/bind/api/ErrorListener

但是,如果我将版本更改为0.12.1,如下所示,它可以工作;

<plugin>
            <groupId>org.jvnet.jaxb2.maven2</groupId>
            <artifactId>maven-jaxb2-plugin</artifactId> …
Run Code Online (Sandbox Code Playgroud)

java xml xsd maven

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

属性"Year"的冲突设置器定义(Springfox-Swagger2)

我的问题与以下问题相同;

Jackson POJOPropertyBuilder在POJO中找到多个setter

但是,因为我使用"springfox-swagger2",我不使用SwaggerSpringMvcPlugin.

有没有办法解决这个问题?

Application.java

/* Makes this Application Run as Spring Boot Application */
@SpringBootApplication
/* Enables Swagger2API for documentation */
@EnableSwagger2
public class Application extends SpringBootServletInitializer { 

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
    LogService.info(Application.class.getName(), "CustomerAPI Service Started");
}

@Bean
public Docket customerApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .groupName("Customer Application")
            .apiInfo(apiInfo())
            .select()
            .paths(myAppPaths())
            .build();
}

private ApiInfo apiInfo() {
    return new ApiInfoBuilder()
            .title("Customer API")
            .description("Some Description to Show")
            .termsOfServiceUrl(null)
            .contact("Test Test")
            .license("Apache License Version 2.0") …
Run Code Online (Sandbox Code Playgroud)

java java-8 swagger-ui spring-boot swagger-2.0

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

为什么 JodaTime 库和 JDK OffsetDateTime 报告太平洋/诺福克时区偏移量不同?哪一个是正确的?

public static void main(String[] args) {
    System.out.println("Norfolk Island times as per Joda Time");
    IntStream.range(1, 13)
            .forEach(month -> System.out.println(DateTime.now((DateTimeZone.forID("Pacific/Norfolk")))
                    .withYear(2023)
                    .withMonthOfYear(month)
                    .withDayOfMonth(10)
                    .withHourOfDay(2)
                    .withMinuteOfHour(10)
                    .withSecondOfMinute(2)
                    .withMillisOfSecond(0)));
    System.out.println("-------------------------------------");
    System.out.println("Norfolk Island times as per JDK OffsetDateTime");
    IntStream.range(1, 13)
            .forEach(month -> System.out.println(OffsetDateTime.now(ZoneId.of("Pacific/Norfolk"))
                    .withYear(2023)
                    .withMonth(month)
                    .withDayOfMonth(10)
                    .withHour(2)
                    .withMinute(10)
                    .withSecond(2)
                    .withNano(0)));
    System.out.println("-------------------------------------");
}
Run Code Online (Sandbox Code Playgroud)

输出:

Norfolk Island times as per Joda Time
2023-01-10T02:10:02.000+12:00
2023-02-10T02:10:02.000+12:00
2023-03-10T02:10:02.000+12:00
2023-04-10T02:10:02.000+11:00
2023-05-10T02:10:02.000+11:00
2023-06-10T02:10:02.000+11:00
2023-07-10T02:10:02.000+11:00
2023-08-10T02:10:02.000+11:00
2023-09-10T02:10:02.000+11:00
2023-10-10T02:10:02.000+12:00
2023-11-10T02:10:02.000+12:00
2023-12-10T02:10:02.000+12:00
-------------------------------------
Norfolk Island times as per JDK OffsetDateTime
2023-01-10T02:10:02+11:00
2023-02-10T02:10:02+11:00
2023-03-10T02:10:02+11:00
2023-04-10T02:10:02+11:00
2023-05-10T02:10:02+11:00 …
Run Code Online (Sandbox Code Playgroud)

java jodatime java-time

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