Home Php C# Sql C C++ Javascript Python Java Go Android Git Linux Asp.net Django .net Node.js Ios Xcode Cocoa Iphone Mysql Tomcat Mongodb Bash Objective-c Scala Visual-studio Apache Elasticsearch Jar Eclipse Jquery Ruby-on-rails Ruby Rubygems Android-studio Spring Lua Sqlite Emacs Ubuntu Perl Docker Swift Amazon-web-services Svn Html Ajax Xml Java-ee Maven Intellij-idea Rvm Macos Unix Css Ipad Postgresql Css3 Json Windows-server Vue.js Typescript Oracle Hibernate Internet-explorer Github Tensorflow Laravel Symfony Redis Html5 Google-app-engine Nginx Firefox Sqlalchemy Lucene Erlang Flask Vim Solr Webview Facebook Zend-framework Virtualenv Nosql Ide Twitter Safari Flutter Bundle Phonegap Centos Sphinx Actionscript Tornado Register | Login | Edit Tags | New Questions | 繁体 | 简体


10 questions online user: 10

0
votes
answers
35 views
+10

最小配置的彈簧啓動

0

默認情況下,Spring Boot具有很多依賴,比如Web/DB/Security以及諸如嵌入式Tomcat等許多其他功能。最小配置的彈簧啓動

在大多數項目中,我只需要依賴注入,閱讀application.properties參數和TestNG支持。沒有其他的。

問題是如何以最小的配置獲得Spring Boot?

+0

只需添加springboot父母的依賴。沒有別的 – pvpkiran

+0

訪問http://start.spring.io/並選擇你真正需要的項目。 – Ele

+1

'spring-boot-starter'是最基本的啓動器......它不包含任何web-dependencies,它就是'spring-boot-starter-web'(以及類似的東西)。 –

沙发
0
3

如果你需要用最小的要求Springboot配置,請訪問此鏈接http://start.spring.io/

enter image description here

正如你所看到的,你可以選擇你的項目的依賴關係。

您可以切換到一個完整的形式有很多選擇:

enter image description here

,並選擇相關性:

enter image description here

+0

我想這是最好的回答:) – Lenar

0
votes
answers
51 views
+10

使用彈簧引導設置Ehcahe 3時出錯1.5

0

我最近從1.4升級到1.5.7的彈簧引導1.5.7,並發現Ehcache已從2.x升級到3.x。配置已全部改變。現在我無法設置緩存配置。使用彈簧引導設置Ehcahe 3時出錯1.5

我試過在Ehcache官方blog上的步驟,但沒有成功。

這裏是我的ehcache-dev.xml

<config 
     xmlns='http://www.ehcache.org/v3' 
     xmlns:jcache='http://www.ehcache.org/v3/jsr107'> 

    <service> 
     <jcache:defaults> 

      <jcache:cache name="categoryCache" template="catalog-cache"/> 
      <jcache:cache name="cfCategoryCache" template="catalog-cache"/> 

      <jcache:cache name="ebooks" template="other-cache"/> 
      <jcache:cache name="userNameToken" template="other-cache"/> 

     </jcache:defaults> 
    </service> 

    <cache-template name="catalog-cache"> 
     <heap unit="entries">200</heap> 
     <expiry> 
      <ttl unit="minutes">10</ttl> 
     </expiry> 
    </cache-template> 

    <cache-template name="other-cache"> 
     <!--<listeners>--> 
     <!--<listener>--> 
     <!--<class>org.terracotta.ehcache.EventLogger</class>--> 
     <!--<event-firing-mode>ASYNCHRONOUS</event-firing-mode>--> 
     <!--<event-ordering-mode>UNORDERED</event-ordering-mode>--> 
     <!--<events-to-fire-on>CREATED</events-to-fire-on>--> 
     <!--<events-to-fire-on>UPDATED</events-to-fire-on>--> 
     <!--<events-to-fire-on>EXPIRED</events-to-fire-on>--> 
     <!--<events-to-fire-on>REMOVED</events-to-fire-on>--> 
     <!--<events-to-fire-on>EVICTED</events-to-fire-on>--> 
     <!--</listener>--> 
     <!--</listeners>--> 
     <heap unit="entries">1000</heap> 
     <expiry> 
      <ttl unit="minutes">15</ttl> 
     </expiry> 
    </cache-template> 
</config> 

application-dev.properties文件包含行:

spring.cache.jcache.config=classpath:ehcache-dev.xml

dev曲線運行時,它會產生錯誤:

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.cache.CacheManager]: Factory method 'jCacheCacheManager' threw exception; nested exception is javax.cache.CacheException: org.ehcache.xml.exceptions.XmlConfigurationException: Error parsing XML configuration at file:/**********/target/********/WEB-INF/classes/ehcache-dev.xml 
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) 
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) 
    ... 135 more 
Caused by: javax.cache.CacheException: org.ehcache.xml.exceptions.XmlConfigurationException: Error parsing XML configuration at file:/**********/target/********/WEB-INF/classes/ehcache-dev.xml 
    at org.ehcache.jsr107.EhcacheCachingProvider$ConfigSupplier.getConfiguration(EhcacheCachingProvider.java:327) 
    at org.ehcache.jsr107.EhcacheCachingProvider.getCacheManager(EhcacheCachingProvider.java:128) 
    at org.ehcache.jsr107.EhcacheCachingProvider.getCacheManager(EhcacheCachingProvider.java:79) 
    at org.springframework.boot.autoconfigure.cache.JCacheCacheConfiguration.createCacheManager(JCacheCacheConfiguration.java:115) 
    at org.springframework.boot.autoconfigure.cache.JCacheCacheConfiguration.jCacheCacheManager(JCacheCacheConfiguration.java:97) 
    at org.springframework.boot.autoconfigure.cache.JCacheCacheConfiguration$$EnhancerBySpringCGLIB$$46f8ca07.CGLIB$jCacheCacheManager$1(<generated>) 
    at org.springframework.boot.autoconfigure.cache.JCacheCacheConfiguration$$EnhancerBySpringCGLIB$$46f8ca07$$FastClassBySpringCGLIB$$fee1b5ae.invoke(<generated>) 
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) 
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358) 
    at org.springframework.boot.autoconfigure.cache.JCacheCacheConfiguration$$EnhancerBySpringCGLIB$$46f8ca07.jCacheCacheManager(<generated>) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
    at java.lang.reflect.Method.invoke(Method.java:498) 
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) 
    ... 136 more 
Caused by: org.ehcache.xml.exceptions.XmlConfigurationException: Error parsing XML configuration at file:/**********/target/********/WEB-INF/classes/ehcache-dev.xml 
    at org.ehcache.xml.XmlConfiguration.<init>(XmlConfiguration.java:167) 
    at org.ehcache.xml.XmlConfiguration.<init>(XmlConfiguration.java:131) 
    at org.ehcache.jsr107.EhcacheCachingProvider$ConfigSupplier.getConfiguration(EhcacheCachingProvider.java:324) 
    ... 150 more 
Caused by: org.xml.sax.SAXParseException; systemId: file:/**********/target/********/WEB-INF/classes/ehcache-dev.xml; lineNumber: 20; columnNumber: 17; cvc-complex-type.2.4.a: Invalid content was found starting with element 'expiry'. One of '{"http://www.ehcache.org/v3":heap-store-settings, "http://www.ehcache.org/v3":disk-store-settings, "http://www.ehcache.org/v3":service-configuration}' is expected. 
    at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source) 
    at org.apache.xerces.util.ErrorHandlerWrapper.error(Unknown Source) 
    at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source) 
    at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source) 
    at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source) 
    at org.apache.xerces.impl.xs.XMLSchemaValidator$XSIErrorReporter.reportError(Unknown Source) 
    at org.apache.xerces.impl.xs.XMLSchemaValidator.reportSchemaError(Unknown Source) 
    at org.apache.xerces.impl.xs.XMLSchemaValidator.handleStartElement(Unknown Source) 
    at org.apache.xerces.impl.xs.XMLSchemaValidator.startElement(Unknown Source) 
    at org.apache.xerces.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source) 
    at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source) 
    at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source) 
    at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source) 
    at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source) 
    at org.apache.xerces.parsers.XMLParser.parse(Unknown Source) 
    at org.apache.xerces.parsers.DOMParser.parse(Unknown Source) 
    at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source) 
    at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:177) 
    at org.ehcache.xml.ConfigurationParser.<init>(ConfigurationParser.java:165) 
    at org.ehcache.xml.XmlConfiguration.parseConfiguration(XmlConfiguration.java:175) 
    at org.ehcache.xml.XmlConfiguration.<init>(XmlConfiguration.java:163) 
    ... 152 more 

現在,如果我沒有錯,它在cache-template元素內接受expiry元素有問題。但是,情況不應該如此,因爲它明確提到hereA <cache-template> element may contain all the same child elements as a <cache> element.cache元素確實具有expiry元素。

我無法理解我在這裏錯過了什麼。任何幫助讚賞。 TIA

沙发
0
1

顯然,問題是按照元素的順序。 heap元素需要在expiry元素之後。

下面的配置工作好嗎:

<cache-template name="catalog-cache">   
    <expiry> 
     <ttl unit="minutes">10</ttl> 
    </expiry> 
    <heap unit="entries">200</heap> 
</cache-template> 

這是沒有意義的,訂單不應該的問題。已與EhCache提交bug-report

0
votes
answers
29 views
+10

在spring啓動時在activeMQ中延遲傳送消息

-1

我想在'x'秒後在任何時間發送一個't'消息,接收器會收到這個消息。這樣做在spring啓動時在activeMQ中延遲傳送消息

,我已經寫了接收器瞬間。沒有任何延遲接收的發送者代碼

@Autowired 
private JmsTemplate jmsTemplate; 
private Queue queue = new ActiveMQQueue("topicName"); 

public void show(String message) { 
    try { 
     System.out.println("Sending message " + message); 
     jmsTemplate.convertAndSend(queue, message, new MessagePostProcessor() { 
      @Override 
      public Message postProcessMessage(Message message) throws JMSException { 
       System.out.println("postProcessMessage executed "); 
       message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, 3 * 60 * 1000); 
       System.out.println("long time " + message 
         .getLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY)); 
       return message; 
      } 
     }); 
     System.out.println("Sending done " + message + " at " + System.currentTimeMillis()); 
    } catch (Exception er) { 
     er.printStackTrace(); 
    } 
} 

和Reciever代碼

@JmsListener(destination = "topicName") 
    public void reciever(String message) { 
     System.out.println("receiving message " + message + " at " + System.currentTimeMillis()); 
    } 

但是消息。

輸出是

發送消息,這是一個消息
postProcessMessage執行長 時間180000
接收到消息,這是一個消息在1514391984964
發送已完成,這是一個消息在1514391984970

配置文件是

@Bean 
    JmsTemplate createJMSTemplate(ConnectionFactory connectionFactory) { 
     JmsTemplate jmsTemplate = new JmsTemplate(); 
     jmsTemplate.setConnectionFactory(connectionFactory); 
     return jmsTemplate; 
    } 

    @Bean 
    ConnectionFactory myActiveMQConnectionFactory() { 
     RedeliveryPolicy redeliveryPolicy = new RedeliveryPolicy(); 
     redeliveryPolicy.setBackOffMultiplier(1); 
     redeliveryPolicy.setUseExponentialBackOff(false); 
     ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616"); 
     connectionFactory.setRedeliveryPolicy(redeliveryPolicy); 
     NetworkConnector networkConnector = new DiscoveryNetworkConnector(); 
     networkConnector.setConsumerTTL(2); 

     return connectionFactory; 
    } 
+0

加入schedulerSupport是否已打開在代理調度的支持? –

沙发
0
0

使用默認配置的activemq不支持延遲消息,您應該首先打開它。

在activemq.conf

<broker xmlns="http://activemq.apache.org/schema/core" brokerName="localhost" dataDirectory="${activemq.data}" schedulerSupport="true"> 
0
votes
answers
31 views
+10

SpringBootApplication無法解析爲Spring工具套件和maven中的類型錯誤

1

我在spring工具套件中創建了maven項目。我創建了具有所需依賴性的pom.xml,但由於「SpringBootApplication無法解析爲類型」而面臨錯誤。 我嘗試了幾個解決方案,如Maven - >更新項目...,清潔項目,刪除Maven(.m2)的本地存儲庫目錄等...我也嘗試創建另一個Maven項目,但仍然是相同的錯誤。SpringBootApplication無法解析爲Spring工具套件和maven中的類型錯誤

我覺得這是eclipse的spring工具套件與maven的問題。 是否有任何解決方案像通過日食或其他任何補丁? 在此先感謝!

的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>io.javabrains.springbootquickstart</groupId> 
    <artifactId>cource.api</artifactId> 
    <version>0.0.1-SNAPSHOT</version> 
    <name>Java Brains Cource API</name> 
    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-parent --> 
    <parent> 
     <groupId>org.springframework.boot</groupId> 
     <artifactId>spring-boot-starter-parent</artifactId> 
     <version>1.5.8.RELEASE</version> 
    </parent> 
    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-parent --> 
    <dependencies> 
     <dependency> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-starter-parent</artifactId> 
      <version>1.5.8.RELEASE</version> 
      <type>pom</type> 
     </dependency> 
    </dependencies> 
    <build> 
     <plugins> 
      <plugin> 
       <groupId>org.springframework.boot</groupId> 
       <artifactId>spring-boot-maven-plugin</artifactId> 
      </plugin> 
     </plugins> 
    </build> 
    <properties> 
     <java.version>1.8</java.version> 
    </properties> 
</project> 
+0

你是否已經嘗試命令mvn乾淨安裝從命令行下你的項目? –

+0

'......不能解析爲類型「表示導入缺失或無法解析。在後一種情況下,「導入...無法解決」是您應該查看的錯誤。你有這樣的錯誤嗎? – howlger

沙发
0
1

您還沒有添加正確的依賴關係。

您應該添加

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

的依賴(在<dependencies>)代替spring-boot-starter-parent。 父只定義了版本,但實際上並沒有添加任何依賴項(您在Maven中將其用作<parent>)。

如果您有測試,還可以添加spring-boot-starter-test

我也建議(在文件 - >新建 - >其他>春季啓動項目也可從STS)使用https://start.spring.io/生成一個工作彈簧引導基地項目。

+0

謝謝! 我明白這個問題,這是因爲提到的helospark的不正確的依賴。 – Ameet

板凳
0
0
<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>io.javabrains.springbootquickstart</groupId> 
<artifactId>cource.api</artifactId> 
<version>0.0.1-SNAPSHOT</version> 
<name>Java Brains Cource API</name> 

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

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

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

<properties> 
    <java.version>1.8</java.version> 
</properties> 

</project> 

將其複製/粘貼到您的POM.xml中。更新Maven項目,它將獲取所需的JAR。

0
votes
answers
35 views
+10

CORS和Spring Websocket

1

我遵循this tutorial構建了一個Spring Boot應用程序,該應用程序爲websockets連接提供服務,但是我無法連接到除Spring Boot本身提供的其他客戶端的這些WebSocket。CORS和Spring Websocket

complete directory in the GitHub repository that accompanies the tutorial包含最終的Spring啓動代碼。我從此存儲庫獲取了index.htmlapp.js文件,並創建了另一個在Node.js服務器上運行的客戶端。之後,我將連接字符串替換爲指向localhost:8080(其中Spring Boot正在運行)。然後我運行Node.js服務器並試圖使用websockets,但它不起作用。

第一個問題很容易通過將.setAllowedOrigins("*")添加到StompEndpointRegistry註冊表中解決。有了這個配置,我設法連接到websocket,但是現在我永遠不會從套接字中獲取消息。

我不知道我錯過了什麼......有人知道什麼是問題嗎?

提取的index.htmlapp.js(更名爲index.js)文件,以及the Node.js server can be found here用於測試目的。要運行它,只需安裝依賴項(npm install),然後發出npm start。服務器將在http://localhost:3000/上進行響應。

沙发
0
0

其實問題很愚蠢。問題是,當我提取的HTML/JS文件到外部應用程序,我改變了所有硬編碼的三個點在代碼中http://localhost:8080/...

var socket = new SockJS('http://localhost:8080/gs-guide-websocket'); 
// ... 
stompClient.subscribe('http://localhost:8080/topic/greetings', cb); 
// ... 
stompClient.send("http://localhost:8080/app/hello", ...); 

,我應該改變的唯一的線是第一個。另外兩個只是subscribesend消息到已打開的套接字上的主題的功能。因此,他們不需要URL作爲前綴...

var socket = new SockJS('http://localhost:8080/gs-guide-websocket'); 
// ... 
stompClient.subscribe('/topic/greetings', cb); 
// ... 
stompClient.send("/app/hello", ...); 
0
votes
answers
40 views
+10

如何使用JpaRepository和嵌套的對象列表進行搜索?

0

說明如何使用JpaRepository和嵌套的對象列表進行搜索?

有一個PersonRepositoryPerson實體, Person類包含List<Qualification>Qualification類有3個簡單的字段。

我嘗試添加自定義方法@Query註釋和使用JPQL得到的結果,但Qualification類領域是不可用於操縱JPQL因爲庫本身包含List<Qualification>代替的Qualification只是一個簡單的領域。

如何通過這些Qualification的嵌套字段進行搜索?

查詢

現在我需要找人實體的列表,其中合格的experienceInMonths大於3小於9和資格的名字字段='Java的。

代碼

Person.java

@Data 
@Entity 
public class Person { 

@Id 
@GeneratedValue(strategy = GenerationType.IDENTITY) 
private String id; 

@NotEmpty 
@Size(min = 2) 
private String name; 

@NotEmpty 
@Size(min = 2) 
private String surname; 

@ElementCollection(targetClass = java.util.ArrayList.class, fetch = FetchType.EAGER) 
private List<Qualification> qualifications = new ArrayList<>(); 

} 

PersonRepository.java

@Repository 
public interface PersonRepository extends JpaRepository<Person, String> { 
} 

Qualification.java

@Data 
@AllArgsConstructor 
public class Qualification implements Serializable { 

    @Id @GeneratedValue 
    private String id; 
    private String name; 
    private String experienceInMonths; 
} 

編輯:不重複的this post,因爲這裏是嵌套對象的集合。不只是單一的參考。

+0

的可能的複製[春季數據JPA找到嵌入對象的屬性(HTTPS ://stackoverflow.com/questions/24441411/spring-data-jpa-find-by-embedded-object-property) –

+0

正如在編輯帖子中提到的,這個問題並沒有相應的提出答案。正如你可以在粘貼的代碼中看到的那樣,對象的'List'有一個問題 - 不僅僅是其中的一個。 – DevDio

沙发
0
1

首先,將experienceInMonthsString更改爲int(否則您無法將該字符串與數字進行比較)。然後,你可以嘗試使用這個「香腸」:

List<Person> findByQualifications_experienceInMonthsGreaterThanAndQualifications_experienceInMonthsLessThanAndName(int experienceGreater, int experienceLess, String name); 

或者你可以嘗試使用這種相當不錯的方法:

@Query("select p from Person p left join p.qualifications q where q.experienceInMonths > ?1 and q.experienceInMonths < ?2 and q.name = ?3") 
List<Person> findByQualification(int experienceGreater, int experienceLess, String name); 
+0

是否在當地爲您工作? JPQL版本給了我'org.hibernate.QueryException:不能解引用標量集合元素:'和香腸之一:'引起:java.lang.IllegalStateException:非法嘗試解引用基本類型的路徑源[null]。即使將Qualification#experienceInMonths類型更改爲'int' – DevDio

+0

@DevDio嘗試將'@ Entity'添加到'Qualification'並將'@ ElementCollection'替換爲'@ OneToMany'(類似的變體適用於我...) – Cepr0

+0

好的,終於搞定了,但它需要在Hibernate中實現單獨的'Qualification'表。其中包含FK給Person(@Entity,@ManyToOne附加字段)+ QualificationRepository是強制性的。 還測試了建議的方法,JPQL的版本工作正常,但'香腸'的名稱需要調整爲: 'findByQualifications_experienceInMonthsGreaterThanAndQualifications_experienceInMonthsLessThanAndQualifications_Name'。 否則會搜索人名。非常感謝@ Cepr0的幫助! – DevDio

0
votes
answers
40 views
+10

未能在對象轉換爲json的過程中懶惰地初始化一個角色集合

0

我是新來的spring,同時從表中獲取記錄與其他表有關係得到這個懶洋洋的初始化錯誤。 我已經在網上閱讀了很多,但沒有得到適當的方法。未能在對象轉換爲json的過程中懶惰地初始化一個角色集合

表1:

@SuppressWarnings("serial") 
@Entity 
public class Terminal extends BaseEntity { 

@Column(length = 100, unique = true) 
private String shortName; 

@Column 
private short number; // short stores up to 32767 value 

@Column 
private String description;  

@OneToMany 
@JoinColumn(name = "terminal_id", referencedColumnName = "uuid") 
@Cascade({ CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DELETE }) 
private Set<BusinessHour> businessHour; 

public String getShortName() { 
    return shortName; 
} 

public void setShortName(String shortName) { 
    this.shortName = shortName; 
} 

public short getNumber() { 
    return number; 
} 

public void setNumber(short number) { 
    this.number = number; 
} 

public String getDescription() { 
    return description; 
} 

public void setDescription(String description) { 
    this.description = description; 
} 
public Set<BusinessHour> getBusinessHour() { 
    return businessHour; 
} 

public void setBusinessHour(Set<BusinessHour> businessHour) { 
    this.businessHour = businessHour; 
} 

表2:

@SuppressWarnings("serial") 
@Entity 
public class BusinessHour extends BaseEntity { 

@Column 
private DayOfWeek dayOfWeek; 

@Column 
private LocalTime startOfOperation; 

@Column 
private LocalTime endOfOperation; 

public DayOfWeek getDayOfWeek() { 
    return dayOfWeek; 
} 
} 

服務代碼:

@Service 
public class TerminalServiceImpl implements TerminalService { 

@Autowired 
TerminalRepository terminalRepository; 


    Iterable<Terminal> allTerminals = terminalRepository.findAll(); 
    List<Terminal> terminalList = new ArrayList<Terminal>(); 
    for (Terminal terminal : allTerminals) { 
     terminalList.add(terminal); 
    } 
    return terminalList; 
} 

終端資源庫合作德:在這裏我調試過程中遇到錯誤

@Transactional 
public interface TerminalRepository extends CrudRepository<Terminal, Long> { 
} 

代碼:

private List<Terminal> updateTerminalList() { 
    List<Terminal> allTerminals = terminalService.fetchAllTerminal(); 
    return allTerminals; 
} 

public void terminalWrapperRun() { 
    try { 
     Payload payload = createTerminalPayload(applicationId); 
     String json3 = object2Json(payload); 
     kafkaRESTUtils.sendServerPayload(json3); 
    } catch (Exception e1) { 
     e1.printStackTrace(); 
    } 
} 

public String object2Json(Object dataArray) throws JsonProcessingException { 
    return mapper.writeValueAsString(dataArray); 
} 

錯誤:

com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: terminal.model.Terminal.businessHour, could not initialize proxy - no Session (through reference chain: 

獲取異常而取對象轉換爲JSON。我發現由於代理對象返回由於提取類型懶惰(我想保持原樣)。

+0

的可能的複製[org.hibernate.LazyInitializationException:無法初始化代理 - 沒有會話?](https://stackoverflow.com/questions/22439306/org-hibernate-lazyinitializationexception-could-not-initialize-proxy -no-sessi) –

沙发
0
0

我相信這個問題與您的ORM默認的LAZY集合加載有關。

@OneToMany 
@JoinColumn(name = "terminal_id", referencedColumnName = "uuid") 
@Cascade({ CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DELETE }) 
private Set<BusinessHour> businessHour; 

@OneToMany註釋具有fetch屬性,默認情況下該屬性設置爲LAZY。

FetchType fetch() default LAZY; 

OneToMany reference

這意味着,當該數據被存取它只會被加載。在你的例子中,當你嘗試創建JSON字符串時會發生這種情況。但是,由於這一點,你不在ORM會話的範圍之內,所以它不知道如何加載數據。

因此你有2個選項。

  1. 更改您的註釋到熱切加載數據(這意味着BusinessHour集將在同一時間作爲父對象

    @OneToMany(取= FetchType.EAGER)

  2. 被加載在ORM會話中執行你的JSON生成(我只會真正推薦這樣做是導致性能問題的第一個選項)

+0

如何在ORM會話中生成json可以協助嗎? – Rishabh

+1

簡要地看一下所提供的代碼,我認爲實現這一目標的最簡單方法是在生成JSON的方法周圍引入一個Transactional註釋。這應該在所需的會話中執行代碼。話雖如此,我認爲這會給代碼帶來誤導性的表示。也許調用JSON代之前,你應該出臺哪些初始化使用businessHour設置一個單獨的方法 同樣,Hibernate.initialize(terminal.getBusinessHour()) – PillHead

板凳
0
0

如果我reca這正是Entity在使用時從EntityManager中分離出來的一種錯誤(它是一個Proxy它無法執行數據庫查詢來檢索數據)。

您可以使用:

@OneToMany(fetch = FetchType.EAGER) 
... 
private Set<BusinessHour> businessHour; 
+0

我不想使用fetchType急於 我們可以有其他的方式來做到這一點 – Rishabh

+0

爲什麼?幾乎沒有任何性能損失,而且您不必更復雜。 Imho這是一個更清潔的解決方案 – LppEdd

地板
0
0

使用FetchType = EAGER意味着對你的實體的任何查詢將加載一大堆註明實體的。

Imho,如果您100%確定您的實體僅用於您的特殊業務案例,這只是一個明智的行爲。在所有其他情況下 - 比如將數據庫編程爲庫,或接受對實體的不同類型的查詢,您應該使用實體圖(https://docs.oracle.com/javaee/7/tutorial/persistence-entitygraphs002.htm)或顯式加載(Hibernate.initialize,join-fetch,請參閱示例https://vladmihalcea.com/hibernate-facts-the-importance-of-fetch-strategy/)。

如果您的使用情況下,僅是轉換,你有兩個很好的選擇:

  • 一個事務性方法內將您的實體JSON(如PillHead建議)
  • 與所有實體明確裝入實體在事務中需要(通過實體圖或Hibernate.initialize),然後在需要它的地方轉換爲JSON。
0
votes
answers
40 views
+10

Intellij - 調試器在maven項目中不工作

0

我遇到了一個問題,我無法在IntelliJ中調試Maven Sprint啓動REST API應用程序。應用程序啓動但不會停在任何斷點處。Intellij - 調試器在maven項目中不工作

此外,當我停止調試器時,我在日誌中看到下面的行,但是我可以看到java進程永不終止,並且當我第二次啓動應用程序時失敗,因爲服務器端口8080仍在使用中。

Disconnected from the target VM, address: '127.0.0.1:53020', transport: 'socket' 
Process finished with exit code -1 

在C: Users Bernhard.IdeaIC2017.3 system log的IntelliJ日誌中,我看到以下錯誤。

2017-12-15 07:22:30,761 [ 11899] INFO - .server.BuildMessageDispatcher - An existing connection was forcibly closed by the remote host 
java.io.IOException: An existing connection was forcibly closed by the remote host 
    at sun.nio.ch.SocketDispatcher.read0(Native Method) 
    at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:43) 
    at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:223) 
    at sun.nio.ch.IOUtil.read(IOUtil.java:192) 
    at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:380) 
    at io.netty.buffer.PooledUnsafeDirectByteBuf.setBytes(PooledUnsafeDirectByteBuf.java:288) 
    at io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:1100) 
    at io.netty.channel.socket.nio.NioSocketChannel.doReadBytes(NioSocketChannel.java:372) 
    at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:123) 
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:644) 
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:579) 
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:496) 
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:458) 
    at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) 
    at java.lang.Thread.run(Thread.java:745) 
沙发
0
0

經過一番搜索之後,我發現問題出在IntelliJ中我的Maven Run/Debug配置。我用它來啓動春季啓動REST API的命令行是

clean package -Drun.profiles=dev-us-east-1 -Drun.jvmArguments=-Denvironment=dev -DskipTests spring-boot:run 

看來,-Drun.jvmArguments=-Denvironment=dev java命令行屬性是罪魁禍首。當我刪除它時,斷點再次工作。

板凳
0
1

您可能可以用引號括住該參數的值。讀取整個命令行字符串的解析器可能因爲-D arg中的-D arg而窒息。

清潔套裝-Drun.profiles = DEV-美國東1 -Drun.jvmArguments = 「-Denvironment =開發」 -DskipTests春天啓動:運行

+0

嗨Jaraon,好oberservation。我確實有雙引號中的「-Denvironment = dev」。我相信Stackoverflow似乎在我的複製粘貼中刪除了它們... –

0
votes
answers
35 views
+10

Spring Boot - 如何禁用Keycloak?

0

我有一個集成了keycloak的Spring Boot項目。現在我想禁用keycloak進行測試。Spring Boot - 如何禁用Keycloak?

我試着將keycloak.enabled=false添加到application.properties,如Keycloak documentation中提到的那樣,但它沒有奏效。

那麼如何禁用它?

+0

你嘗試只刪除依賴於gradle這個build文件你的Maven的 部分keycloak彈簧引導的人嗎? –

+0

不,我實際上想在不去除keycloak依賴關係的情況下禁用它。 –

沙发
0
1

它應該可以工作,但基於jira ticket的最後一條評論,看起來並不是這樣。

正如你可以排除增加對keycloak春天開機自動配置的描述說明你application.propertiesspring.autoconfigure.exclude=org.keycloak.adapters.springboot.KeycloakSpringBootConfiguration

+2

如果您還啓用了Spring Security,則它不起作用,'enable'標誌僅適用於單獨使用Spring Boot Adapter。當使用Spring Secuiryt時,我們還有一張支持國旗的票。 –

0
votes
answers
48 views
+10

彈簧引導應用程序在啓動後立即關閉(schedular)

0

我正在瀏覽彈簧調度程序指南(https://spring.io/guides/gs/scheduling-tasks/),但我的彈簧引導應用程序在啓動後立即終止。我檢查了所有的依賴關係,他們似乎很好。我的輸出是彈簧引導應用程序在啓動後立即關閉(schedular)

"C:Program FilesJavajdk1.8.0_111injava" -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:60501,suspend=y,server=n -Dfile.encoding=UTF-8 -classpath "C:Program FilesJavajdk1.8.0_111jrelibcharsets.jar;C:Program FilesJavajdk1.8.0_111jrelibdeploy.jar;C:Program FilesJavajdk1.8.0_111jrelibextaccess-bridge-64.jar;C:Program FilesJavajdk1.8.0_111jrelibextcldrdata.jar;C:Program FilesJavajdk1.8.0_111jrelibextdnsns.jar;C:Program FilesJavajdk1.8.0_111jrelibextjaccess.jar;C:Program FilesJavajdk1.8.0_111jrelibextjfxrt.jar;C:Program FilesJavajdk1.8.0_111jrelibextlocaledata.jar;C:Program FilesJavajdk1.8.0_111jrelibext
ashorn.jar;C:Program FilesJavajdk1.8.0_111jrelibextsunec.jar;C:Program FilesJavajdk1.8.0_111jrelibextsunjce_provider.jar;C:Program FilesJavajdk1.8.0_111jrelibextsunmscapi.jar;C:Program FilesJavajdk1.8.0_111jrelibextsunpkcs11.jar;C:Program FilesJavajdk1.8.0_111jrelibextzipfs.jar;C:Program FilesJavajdk1.8.0_111jrelibjavaws.jar;C:Program FilesJavajdk1.8.0_111jrelibjce.jar;C:Program FilesJavajdk1.8.0_111jrelibjfr.jar;C:Program FilesJavajdk1.8.0_111jrelibjfxswt.jar;C:Program FilesJavajdk1.8.0_111jrelibjsse.jar;C:Program FilesJavajdk1.8.0_111jrelibmanagement-agent.jar;C:Program FilesJavajdk1.8.0_111jrelibplugin.jar;C:Program FilesJavajdk1.8.0_111jrelib
esources.jar;C:Program FilesJavajdk1.8.0_111jrelib
t.jar;C:my-datacodespring-guidesspring-schedular	argetclasses;C:Usersashis.m2
epositoryorgspringframeworkootspring-boot-starter1.5.9.RELEASEspring-boot-starter-1.5.9.RELEASE.jar;C:Usersashis.m2
epositoryorgspringframeworkootspring-boot1.5.9.RELEASEspring-boot-1.5.9.RELEASE.jar;C:Usersashis.m2
epositoryorgspringframeworkspring-context4.3.13.RELEASEspring-context-4.3.13.RELEASE.jar;C:Usersashis.m2
epositoryorgspringframeworkspring-aop4.3.13.RELEASEspring-aop-4.3.13.RELEASE.jar;C:Usersashis.m2
epositoryorgspringframeworkspring-beans4.3.13.RELEASEspring-beans-4.3.13.RELEASE.jar;C:Usersashis.m2
epositoryorgspringframeworkspring-expression4.3.13.RELEASEspring-expression-4.3.13.RELEASE.jar;C:Usersashis.m2
epositoryorgspringframeworkootspring-boot-autoconfigure1.5.9.RELEASEspring-boot-autoconfigure-1.5.9.RELEASE.jar;C:Usersashis.m2
epositoryorgspringframeworkootspring-boot-starter-logging1.5.9.RELEASEspring-boot-starter-logging-1.5.9.RELEASE.jar;C:Usersashis.m2
epositorychqoslogbacklogback-classic1.1.11logback-classic-1.1.11.jar;C:Usersashis.m2
epositorychqoslogbacklogback-core1.1.11logback-core-1.1.11.jar;C:Usersashis.m2
epositoryorgslf4jjcl-over-slf4j1.7.25jcl-over-slf4j-1.7.25.jar;C:Usersashis.m2
epositoryorgslf4jjul-to-slf4j1.7.25jul-to-slf4j-1.7.25.jar;C:Usersashis.m2
epositoryorgslf4jlog4j-over-slf4j1.7.25log4j-over-slf4j-1.7.25.jar;C:Usersashis.m2
epositoryorgspringframeworkspring-core4.3.13.RELEASEspring-core-4.3.13.RELEASE.jar;C:Usersashis.m2
epositoryorgyamlsnakeyaml1.17snakeyaml-1.17.jar;C:Usersashis.m2
epositoryorgslf4jslf4j-api1.7.25slf4j-api-1.7.25.jar;C:UsersashisAppDataLocalJetBrainsToolboxappsIDEA-Uch-0172.3544.35libidea_rt.jar" com.ashish.springschedular.SpringSchedularApplication 
Connected to the target VM, address: '127.0.0.1:60501', transport: 'socket' 

    . ____   _   __ _ _ 
/\/___'_ __ _ _(_)_ __ __ _     
(()\___ | '_ | '_| | '_ / _` |     
\/ ___)| |_)| | | | | || (_| | )))) 
    ' |____| .__|_| |_|_| |_\__, |//// 
=========|_|==============|___/=/_/_/_/ 
:: Spring Boot ::  (v1.5.9.RELEASE) 

2017-12-18 06:24:30.882 INFO 11836 --- [   main] c.a.s.SpringSchedularApplication   : Starting SpringSchedularApplication on DESKTOP-SP4170I with PID 11836 (C:my-datacodespring-guidesspring-schedular	argetclasses started by ashish in C:my-datacodespring-guidesspring-schedular) 
2017-12-18 06:24:30.882 INFO 11836 --- [   main] c.a.s.SpringSchedularApplication   : No active profile set, falling back to default profiles: default 
2017-12-18 06:24:31.053 INFO 11836 --- [   main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.spring[email protected]1d8bd0de: startup date [Mon Dec 18 06:24:31 EST 2017]; root of context hierarchy 
2017-12-18 06:24:33.115 INFO 11836 --- [   main] o.s.j.e.a.AnnotationMBeanExporter  : Registering beans for JMX exposure on startup 
Disconnected from the target VM, address: '127.0.0.1:60501', transport: 'socket' 
2017-12-18 06:24:33.161 INFO 11836 --- [   main] c.a.s.SpringSchedularApplication   : Started SpringSchedularApplication in 2.997 seconds (JVM running for 4.005) 
2017-12-18 06:24:33.161 INFO 11836 --- [  Thread-2] s.c.a.AnnotationConfigApplicationContext : Closing org.spring[email protected]1d8bd0de: startup date [Mon Dec 18 06:24:31 EST 2017]; root of context hierarchy 
2017-12-18 06:24:33.161 INFO 11836 --- [  Thread-2] o.s.j.e.a.AnnotationMBeanExporter  : Unregistering JMX-exposed beans on shutdown 

Process finished with exit code 0 

我主要的應用程序代碼:

import org.springframework.boot.SpringApplication; 
import org.springframework.boot.autoconfigure.SpringBootApplication; 

@SpringBootApplication 
public class SpringSchedularApplication { 

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

我的雙響炮:

<?xml version="1.0" encoding="UTF-8"?> 
<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.ashish</groupId> 
    <artifactId>spring-schedular</artifactId> 
    <version>0.0.1-SNAPSHOT</version> 
    <packaging>jar</packaging> 

    <name>spring-schedular</name> 
    <description>Demo project for Spring Boot</description> 

    <parent> 
     <groupId>org.springframework.boot</groupId> 
     <artifactId>spring-boot-starter-parent</artifactId> 
     <version>1.5.9.RELEASE</version> 
     <relativePath/> <!-- lookup parent from repository --> 
    </parent> 

    <properties> 
     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 
     <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> 
     <java.version>1.8</java.version> 
    </properties> 

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

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

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

    <repositories> 
     <repository> 
      <id>spring-snapshots</id> 
      <name>Spring Snapshots</name> 
      <url>https://repo.spring.io/snapshot</url> 
      <snapshots> 
       <enabled>true</enabled> 
      </snapshots> 
     </repository> 
     <repository> 
      <id>spring-milestones</id> 
      <name>Spring Milestones</name> 
      <url>https://repo.spring.io/milestone</url> 
      <snapshots> 
       <enabled>false</enabled> 
      </snapshots> 
     </repository> 
    </repositories> 

    <pluginRepositories> 
     <pluginRepository> 
      <id>spring-snapshots</id> 
      <name>Spring Snapshots</name> 
      <url>https://repo.spring.io/snapshot</url> 
      <snapshots> 
       <enabled>true</enabled> 
      </snapshots> 
     </pluginRepository> 
     <pluginRepository> 
      <id>spring-milestones</id> 
      <name>Spring Milestones</name> 
      <url>https://repo.spring.io/milestone</url> 
      <snapshots> 
       <enabled>false</enabled> 
      </snapshots> 
     </pluginRepository> 
    </pluginRepositories> 


</project> 

任我調度文件:

import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
import org.springframework.scheduling.annotation.Scheduled; 
import org.springframework.stereotype.Component; 

import java.text.DateFormat; 
import java.util.Date; 

import static java.text.DateFormat.LONG; 
import static java.text.DateFormat.getDateInstance; 
import static java.util.Locale.US; 

@Component 
public class ScheduledTask { 
    private static final Logger log = LoggerFactory.getLogger(ScheduledTask.class); 
    private static final DateFormat dateFormat = getDateInstance(LONG, US); 

    @Scheduled(fixedRate = 5000) 
    public void readCurrentTime(){ 
     log.info("The time is now[]", dateFormat.format(new Date())); 
    } 
} 
+3

將'@ EnableScheduling'添加到您的應用程序類中。 –

+0

@ M.Deinum非常感謝。有效 – Ashish

沙发
0
1

雖然春季啓動系統能夠大量的東西取決於你的依賴關係對於調度和異步不這樣做。您仍然需要分別通過添加@EnableScheduling@EnableAsync來手動啓用該功能。

在您的情況下,將@EnableScheduling添加到您的應用程序類就足夠了。

@SpringBootApplication 
@EnableScheduling 
public class SpringSchedularApplication { 

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

有了這個調度將被啓用,因爲有一個調度線程仍在運行應用程序不會關閉。