Spring config for connecting to Postgres. Need bean: 'org.flywaydb.core.internal.jdbc.JdbcTemplate' - spring

I'm getting this error when trying to run my Spring application.
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-09-22 23:55:45.397 ERROR 36321 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in com.example.demo.dao.UserDataAccessService required a bean of type 'org.flywaydb.core.internal.jdbc.JdbcTemplate' that could not be found.
Action:
Consider defining a bean of type 'org.flywaydb.core.internal.jdbc.JdbcTemplate' in your configuration.
The application works when I use my fakeUserData file. It seems like there is a dependency issue, but I've double checked and it looks like the dependencies are all there.
Pom.xml
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</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-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.yml
app:
datasource:
jdbc-url: jdbc:postgresql://localhost:5432/springbootpostgresdb
username: postgres
password: password
pool-size: 30
UserDataAccessService.java
package com.example.demo.dao;
import com.example.demo.model.User;
import org.flywaydb.core.internal.jdbc.JdbcTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.sql.SQLException;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
#Repository("postgresql")
public class UserDataAccessService implements Userdao {
private final JdbcTemplate jdbcTemplate;
#Autowired
public UserDataAccessService(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
#Override
public int insertUser(UUID id, User user) {
return 0;
}
#Override
public int deleteUserById(UUID id) {
return 0;
}
#Override
public int updateUserById(UUID id, User user) {
return 0;
}
#Override
public Optional<User> selectUserById(UUID id) {
return Optional.empty();
}
#Override
public List<User> selectAllUsers() {
final String sql = "SELECT id,name FROM userProfile";
try {
return jdbcTemplate.query(sql, (resultSet) -> {
UUID id = UUID.fromString(resultSet.getString("id"));
String name = resultSet.getString("name");
return new User(id, name);
});
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
}
PostgresDataSource.java
package com.example.demo.datasource;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
public class PostgresDataSource {
#Bean
#ConfigurationProperties("app.datasource")
public HikariDataSource hikariDataSource() {
return DataSourceBuilder
.create()
.type(HikariDataSource.class)
.build();
}
}

Hi I had directly the same problem.
Problem was That when you automatically import library, there are two options.
Flyway or Springframework.
If you import flyway, than you have this problem.
import org.flywaydb.core.internal.jdbc.JdbcTemplate;
If you import spriongwramework everything is OK
import org.springframework.jdbc.core.JdbcTemplate;

I found two problem.
as #stefic said, you should modify your import jdbcTemplate
you should modify your jdbcTemplate query
UserDataAccessService.java
#Override
public List<User> selectAllUsers() {
final String sql = "SELECT id,name FROM userProfile";
return jdbcTemplate.query(sql, (resultSet, i) -> { // <----- add second parameter `i`
UUID id = UUID.fromString(resultSet.getString("id"));
String name = resultSet.getString("name");
return new User(id, name);
});
}

Related

Field departmentrepositoryy in service.DepartementServiceimpl required a bean of type 'repository.DepartmentRepository' that could not be found

entity
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Department {
public long getDepartment_id() {
return department_id;
}
public void setDepartment_id(long department_id) {
this.department_id = department_id;
}
public String getDepartment_name() {
return department_name;
}
public Department(long department_id, String department_name, String department_address, String department_code) {
this.department_id = department_id;
this.department_name = department_name;
this.department_address = department_address;
this.department_code = department_code;
}
public void setDepartment_name(String department_name) {
this.department_name = department_name;
}
public String getDepartment_address() {
return department_address;
}
public void setDepartment_address(String department_address) {
this.department_address = department_address;
}
public String getDepartement_code() {
return department_code;
}
public void setDepartement_code(String department_code) {
this.department_code = department_code;
}
public Department() {
super();
}
#Override
public String toString() {
return "Department{" +
"departement_id=" + department_id +
", departement_name='" + department_name + '\'' +
", departement_address='" + department_address + '\'' +
", departement_code='" + department_code + '\'' +
'}';
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long department_id;
private String department_name;
private String department_address;
private String department_code;
}
department controller
import entity.Department;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import service.DepartmentService;
#RestController
public class DepartmentController {
#Autowired
public DepartmentService departmentServicee;
#PostMapping("/departments")
public Department saveDepartment(#RequestBody Department department)
{
return departmentServicee.saveDepartment(department);
}
}
Department service
import org.springframework.stereotype.Component;
import entity.Department;
import org.springframework.stereotype.Service;
public interface DepartmentService {
public Department saveDepartment(Department department);
}
department service impl
import entity.Department;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import repository.DepartmentRepository;
#Service
public class DepartementServiceimpl implements DepartmentService {
#Autowired
public DepartmentRepository departmentrepositoryy;
#Override
public Department saveDepartment(Department department) {
return departmentrepositoryy.save(department);
}
}
Department repository
import entity.Department;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.FluentQuery;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
#Repository
public interface DepartmentRepository extends JpaRepository<Department,Long> {
}
application.properties
server.port = 9009
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=sa
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
pom.xml
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.saketh</groupId>
<artifactId>spring_boot_Real</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring_boot_Real</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-devtools -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa -->
<!--<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
</dependency>-->
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<scope>runtime</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate.javax.persistence/hibernate-jpa-2.1-api -->
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
**
Unable to get my mistake tried most of the available solutions
what did I miss?
I did add all the files that i have used , please let me know any other required
Thanks
**
file structure

if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No context holder available for step scope

I am using Spring Boot v2.6.2 and Spring Batch and getting below error:
ustom destroy method 'close' on bean with name 'compositeItemWriter' threw an exception: org.springframework.beans.factory.support.ScopeNotActiveException: Error creating bean with name 'scopedTarget.xmlDelegateItemWriter': Scope 'step' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No context holder available for step scope
MainApp.java
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.item.database.JdbcBatchItemWriter;
import org.springframework.batch.item.database.builder.JdbcBatchItemWriterBuilder;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder;
import org.springframework.batch.item.support.CompositeItemWriter;
import org.springframework.batch.item.support.builder.CompositeItemWriterBuilder;
import org.springframework.batch.item.xml.StaxEventItemWriter;
import org.springframework.batch.item.xml.builder.StaxEventItemWriterBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.oxm.xstream.XStreamMarshaller;
import javax.sql.DataSource;
import java.util.*;
#SpringBootApplication
#EnableBatchProcessing
public class CompositeItemWriterJobApplication {
#Autowired
private JobBuilderFactory jobBuilderFactory;
#Autowired
private StepBuilderFactory stepBuilderFactory;
#Bean(destroyMethod="")
#StepScope
public FlatFileItemReader<Customer> compositeWriterItemReader(#Value("#{jobParameters['customerFile']}") Resource inputFile) {
return new FlatFileItemReaderBuilder<Customer>()
.name("compositeWriterItemReader")
.resource(inputFile)
.delimited()
.names("firstName", "middleInitial", "lastName", "address", "city", "state", "zip", "email")
.targetType(Customer.class)
.build();
}
#Bean(destroyMethod="")
#StepScope
public StaxEventItemWriter<Customer> xmlDelegateItemWriter(#Value("#{jobParameters['outputFile']}") Resource outputFile){
Map<String, Class> aliases = new HashMap<>();
aliases.put("customer", Customer.class);
XStreamMarshaller marshaller = new XStreamMarshaller();
marshaller.setAliases(aliases);
marshaller.afterPropertiesSet();
return new StaxEventItemWriterBuilder<Customer>()
.name("customerItemWriter")
.resource(outputFile)
.marshaller(marshaller)
.rootTagName("customers")
.build();
}
#Bean
public JdbcBatchItemWriter<Customer> jdbcDelgateItemWriter(DataSource dataSource) {
return new JdbcBatchItemWriterBuilder<Customer>()
.namedParametersJdbcTemplate(new NamedParameterJdbcTemplate(dataSource))
.sql("INSERT INTO CUSTOMER (first_name, middle_initial, last_name, address, city, state, email) " +
"VALUES(:firstName,:middleInitial, :lastName, :address, :city, :state, :zip, :email)")
.beanMapped()
.build();
}
#Bean
public CompositeItemWriter<Customer> compositeItemWriter() throws Exception {
return new CompositeItemWriterBuilder<Customer>()
.delegates(Arrays.asList(xmlDelegateItemWriter(null),
jdbcDelgateItemWriter(null)))
.build();
}
#Bean
public Step compositeWriterStep() throws Exception {
return this.stepBuilderFactory.get("compositeWriterStep")
.<Customer, Customer>chunk(10)
.reader(compositeWriterItemReader(null))
.writer(compositeItemWriter())
.build();
}
#Bean
public Job compositeWriterJob() throws Exception {
return this.jobBuilderFactory.get("compositeWriterJob")
.start(compositeWriterStep())
.build();
}
public static void main(String[] args) {
SpringApplication.run(CompositeItemWriterJobApplication.class,
"customerFile=/data/customer.csv",
"outputFile=/output/customer.xml");
}
}
pom.xml
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>composite-item-writer-job</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>composite-item-writer-job</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
</dependency>
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.18</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
Note: I also used #Scope(value = "step", proxyMode = ScopedProxyMode.TARGET_CLASS), but no luck.
Bean
#Bean
public org.springframework.batch.core.scope.StepScope stepScope() {
final StepScope stepScope = new org.springframework.batch.core.scope.StepScope();
stepScope.setAutoProxy(true);
return stepScope;
}
application.yml
spring:
batch:
initialize-schema: always
datasource:
driverClassName: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test
username: 'root'
password: 'root'
platform: mysql
main:
allow-bean-definition-overriding: true
Things are still not working!
I encountered the same problem. For me, the solution was to add “#StepScope” on the methods calling the method with “#StepScope” and the jobParameters. In this example, I would try to annotate the method compositeItemWriter with “#StepScope”. You will probably need to do it with jdbcDelgateItemWriter.
#Bean
#StepScope
public CompositeItemWriter<Customer> compositeItemWriter() throws Exception {
return new CompositeItemWriterBuilder<Customer>()
.delegates(Arrays.asList(xmlDelegateItemWriter(null),
jdbcDelgateItemWriter(null)))
.build();
}

com.mongodb.MongoSocketOpenException: Exception opening socket with spring boot and mongodb cloud

Please suggest any solution for the below exception which is occuring while running my rest api while executing springboot application with mongodb cloud db. I have created collection in mongodb as well and configured below properties.
com.mongodb.MongoSocketOpenException: Exception opening socket
at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:70) ~[mongodb-driver-core-4.1.1.jar:na]
at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:143) ~[mongodb-driver-core-4.1.1.jar:na]
at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.lookupServerDescription(DefaultServerMonitor.java:188) ~[mongodb-driver-core-4.1.1.jar:na]
at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:144) ~[mongodb-driver-core-4.1.1.jar:na]
at java.base/java.lang.Thread.run(Thread.java:832) ~[na:na]
Caused by: java.net.ConnectException: Connection refused: no further information
at java.base/sun.nio.ch.Net.pollConnect(Native Method) ~[na:na]
at java.base/sun.nio.ch.Net.pollConnectNow(Net.java:589) ~[na:na]
at java.base/sun.nio.ch.NioSocketImpl.timedFinishConnect(NioSocketImpl.java:549) ~[na:na]
at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:597) ~[na:na]
at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:333) ~[na:na]
at java.base/java.net.Socket.connect(Socket.java:648) ~[na:na]
at com.mongodb.internal.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:78) ~[mongodb-driver-core-4.1.1.jar:na]
at com.mongodb.internal.connection.SocketStream.initializeSocket(SocketStream.java:79) ~[mongodb-driver-core-4.1.1.jar:na]
at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:65) ~[mongodb-driver-core-4.1.1.jar:na]
... 4 common frames omitted
Model class
------------
package com.praveen.entity;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import lombok.Data;
#Document
public class Products {
#Id
private String id;
private Integer p_id;
private String p_name;
private Integer p_cost;
private Integer countInStock;
private Integer numReviews;
private String image;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Integer getP_id() {
return p_id;
}
public void setP_id(Integer p_id) {
this.p_id = p_id;
}
public String getP_name() {
return p_name;
}
public void setP_name(String p_name) {
this.p_name = p_name;
}
public Integer getP_cost() {
return p_cost;
}
public void setP_cost(Integer p_cost) {
this.p_cost = p_cost;
}
public Integer getCountInStock() {
return countInStock;
}
public void setCountInStock(Integer countInStock) {
this.countInStock = countInStock;
}
public Integer getNumReviews() {
return numReviews;
}
public void setNumReviews(Integer numReviews) {
this.numReviews = numReviews;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
#Override
public String toString() {
return "Products [id=" + id + ", p_id=" + p_id + ", p_name=" + p_name + ", p_cost=" + p_cost + ", countInStock="
+ countInStock + ", numReviews=" + numReviews + ", image=" + image + "]";
}
}
RestController class
---------------------
package com.praveen.rest;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RestController;
import com.praveen.entity.Products;
import com.praveen.service.ProductsService;
#RestController
public class ProductsRestController {
#Autowired
private ProductsService service;
#GetMapping("/products")
public ResponseEntity<List<Products>> getProducts(){
List<Products> allProducts = service.getAllProducts();
if(allProducts != null) {
return new ResponseEntity<List<Products>>(allProducts, HttpStatus.OK);
}else {
return new ResponseEntity<List<Products>>(HttpStatus.BAD_REQUEST);
}
}
}
Service class
--------------
package com.praveen.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.praveen.entity.Products;
import com.praveen.repository.ProductsRepository;
#Service
public class ProductsServiceImpl implements ProductsService {
#Autowired
private ProductsRepository prodRepo;
#Override
public List<Products> getAllProducts() {
List<Products> productsList = prodRepo.findAll();
if(productsList != null) {
System.out.println(productsList);
return productsList;
}
return null;
}
}
Repository
-----------
package com.praveen.repository;
import java.io.Serializable;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.praveen.entity.Products;
#Repository
public interface ProductsRepository extends MongoRepository<Products, Serializable> {
}
application.properties
-----------------------
spring.data.mongodb.url = mongodb+srv://praveen:praveen#cluster0.qrvkm.mongodb.net/miniproject?retryWrites=true&w=majority
spring.data.mongodb.database = products
spring.data.mongodb.port = 27017
spring.data.mongodb.repositories.enabled=true
pom.xml
-------
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.praveen</groupId>
<artifactId>NgRx-Products</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>05-MiniProject-NgRx-Products</name>
<description>NgRx package with Products data using springboot</description>
<properties>
<java.version>15</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</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>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
Please suggest any solution for the above exception, I have given all my files in the above.
Try adding this annotation to your main class file
#EnableAutoConfiguration(exclude={MongoAutoConfiguration.class})
Search services in start.
open it.
search for mongodb there.
start/restart mongodb services from there.
It should work properly.
this exception occurs due to mongodb incorrect port in application properties. So only changing spring.data.mongodb.port=27017 in application.properties file made it work. Also make sure you started mongodb server locally.
Check the connect to MongoDB sever locally with url:portNumber mentioned in the application.properties from where your code is getting executed.

Spring Boot WebSocket with embedded ActiveMQ Broker

I tried to change an web application from simple broker to an embedded ActiveMq Broker with stomp using Spring boot 1.5.4 but always getting an error on start up
Caused by: java.lang.IllegalArgumentException: No handlers
at org.springframework.util.Assert.isTrue(Assert.java:92) ~[spring-core-4.3.9.RELEASE.jar:4.3.9.RELEASE]
at org.springframework.web.socket.messaging.SubProtocolWebSocketHandler.start(SubProtocolWebSocketHandler.java:244) ~[spring-websocket-4.3.9.RELEASE.jar:4.3.9.RELEASE]
at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:175) ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]
... 15 common frames omitted
I reduced the failure with an simple example
POM File *
<?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.example</groupId>
<artifactId>websocket</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>websocket</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.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-activemq</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-stomp</artifactId>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-net</artifactId>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-core</artifactId>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.2.Final</version>
</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>
</project>
Application Class
package com.example.websocket;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class WebsocketApplication {
public static void main(String[] args) {
SpringApplication.run(WebsocketApplication.class, args);
}
}
WebSocketConfig Class
package com.example.websocket;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurationSupport;
#Configuration
#EnableWebSocket
#EnableWebSocketMessageBroker
#EnableJms
public class WebSocketConfig extends WebSocketMessageBrokerConfigurationSupport {
#Value("${spring.activemq.user}")
private String mqUser;
#Value("${spring.activemq.password}")
private String mqPasword;
#Override
public void configureMessageBroker(final MessageBrokerRegistry config) {
config.enableStompBrokerRelay("/topic") //
.setRelayHost("localhost") //
.setRelayPort(61613) //
.setClientLogin(mqUser) //
.setClientPasscode(mqPasword) //
;
config.setApplicationDestinationPrefixes("/app");
}
#Override
public void registerStompEndpoints(final StompEndpointRegistry registry) {
registry.addEndpoint("/websocket").withSockJS();
}
}
application.yml
spring:
activemq:
broker-url: stomp://localhost:61613
user: user
password: pass
Someone knows my mistake?
I found the solution. My problem was the EnableWebSocketMessageBroker Annotation and missing deployment of ActiveMQ Broker
Remove the application.yml and change WebSocketConfig class to
package com.example.websocket;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.jmx.ManagementContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurationSupport;
#Configuration
#EnableWebSocket
public class WebSocketConfig extends WebSocketMessageBrokerConfigurationSupport {
#Override
public void configureMessageBroker(final MessageBrokerRegistry config) {
config.enableStompBrokerRelay("/topic") //
.setRelayHost("localhost") //
.setRelayPort(61613);
config.setApplicationDestinationPrefixes("/app");
}
#Override
public void registerStompEndpoints(final StompEndpointRegistry registry) {
registry.addEndpoint("/websocket").withSockJS();
}
#Bean(initMethod = "start", destroyMethod = "stop")
public BrokerService broker() throws Exception {
final BrokerService broker = new BrokerService();
broker.addConnector("stomp://localhost:61613");
broker.setPersistent(false);
final ManagementContext managementContext = new ManagementContext();
managementContext.setCreateConnector(true);
broker.setManagementContext(managementContext);
return broker;
}
}
works for me.

spring framework 3.2.9 annotations

i try to use spring framework 3.2.9
that's my 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.mkyong.common</groupId>
<artifactId>3_2_9</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>3_2_9</name>
<url>http://maven.apache.org</url>
<dependencies>
<!-- Spring framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.9.RELEASE</version>
</dependency>
</dependencies>
<build>
<finalName>3_2_9</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<webXml>WebContent\WEB-INF\web.xml</webXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
and i have 3 classes
*hello/MessageService.java:
package hello;
public interface MessageService {
String getMessage();
}
*hello/MessagePrinter.java
package hello;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
#Component
public class MessagePrinter {
final private MessageService service;
#Autowired
public MessagePrinter(MessageService service) {
this.service = service;
}
public void printMessage() {
System.out.println(this.service.getMessage());
}
}
*hello/Application.java
package hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.*;
#Configuration
#ComponentScan
public class Application {
#Bean
MessageService mockMessageService() {
return new MessageService() {
public String getMessage() {
return "Hello World!";
}
};
}
public static void main(String[] args) {
ApplicationContext context =
new AnnotationConfigApplicationContext(Application.class);
MessagePrinter printer = context.getBean(MessagePrinter.class);
printer.printMessage();
}
}
but the import cannot be resolved and the annotations that i have used are no known.any one can help me..
The #Autowired annotation resides in the spring-beans project, try adding the following dependency to your pom:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>3.2.9.RELEASE</version>
</dependency>

Resources