Spring Cloud config client not picking endpoints from Config server - java

Eureka configuration is pulled perfectly from the config server but the endpoints are not pulled from config-server.
Please let me know if I am missing something.
#Service
#RefreshScope
public class OrderService {
#Autowired
private OrderRepo orderRepo;
#Autowired
#Lazy
private RestTemplate restTemplate;
#Value("${payment.endpoints}")
private String DO_PAYMENT_URL;
public TransactionResponse saveOrder(TransactionRequest request) {
System.err.println(request);
TransactionResponse response = new TransactionResponse();
Order order = request.getOrder();
Payment payment = request.getPayment();
payment.setOrderId(order.getId());
response.setOrder(orderRepo.save(order));
// rest call
Payment paymentResponse =
// restTemplate.postForObject("http://localhost:8083/payment/doPayment",payment,
// Payment.class);
// restTemplate.postForObject("http://PAYMENT-SERVICE/payment/doPayment",payment,
// Payment.class);
restTemplate.postForObject(DO_PAYMENT_URL + "/doPayment", payment, Payment.class);
response.setMessage(
paymentResponse.getStatus().equalsIgnoreCase("success") ? "payment successful" : "payment failed");
response.setTransactionId(paymentResponse.getTransactionId());
return response;
}
}
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.12.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.hk</groupId>
<artifactId>order-service</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>order-service</name>
<description>order service</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Hoxton.SR11</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
git-config-file :
https://gitlab.com/nickybesra/microservice-cloud-config/-/blob/main/application.yml
ORDER-SERVICE bootstrap.yml:
spring:
cloud:
config:
uri:
- http://localhost:9196
microservice code :
https://gitlab.com/nickybesra/microservice-2021

Related

RequestBody is not returning username - SpringBoot

I'm making a POST request to authenticate the API that I'm implementing, but I have the following problem:
My username is not being returned:
however, my password is, and I'm not understanding why:
Below I will be sending my source code for better understanding...
Class: AuthController.java
#RestController
#RequestMapping("/auth")
public class AuthController {
#Autowired
AuthenticationManager authenticationManager;
#Autowired
JwtTokenProvider jwtTokenProvider;
#Autowired
UserRepository repository;
#ApiOperation(value = "Authenticate a user by credentials") //Swagger endpoint description
#PostMapping(value="/signin", produces = { "application/json", "application/xml", "application/x-yaml" }, consumes = {
"application/json", "application/xml", "application/x-yaml" })
public ResponseEntity singin(#RequestBody AccountCredentialsVO data) throws Exception {
try {
var username = data.getUserName();
var password = data.getPassword();
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
var user = repository.findByUserName(username);
var token = "";
if(user != null) {
token = jwtTokenProvider.createToken(username, user.getRoles());
}else {
throw new UsernameNotFoundException("Username " + username + " not found!");
}
Map<Object, Object> model = new HashMap<>();
model.put("username", username);
model.put("token", token);
return ok(model);
} catch (Exception e) {
throw new BadCredentialsException("Invalid username/password supplied!");
}
}
}
Class: AccountCredentialsVO.java
public class AccountCredentialsVO implements Serializable {
private static final long serialVersionUID = 1L;
#Column(name = "username")
private String username;
private String password;
public String getUserName() {
return username;
}
public void setUserName(String userName) {
this.username = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public int hashCode() {
return Objects.hash(password, username);
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AccountCredentialsVO other = (AccountCredentialsVO) obj;
return Objects.equals(password, other.password) && Objects.equals(username, other.username);
}
}
The 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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>br.com.andrefilipeos</groupId>
<artifactId>rest-with-springboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<description>Creating API RESTFul with Spring Boot 2.x</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>11</java.version>
</properties>
<dependencies>
<!-- for Spring-boot Support -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- for Tests Support -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.dozermapper</groupId>
<artifactId>dozer-core</artifactId>
<version>6.5.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- for XML support-->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
<!-- for YML or YAML support-->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
</dependency>
<!-- for HATEOAS Support -->
<dependency>
<groupId>org.springframework.hateoas</groupId>
<artifactId>spring-hateoas</artifactId>
</dependency>
<!-- for Swagger Support -->
<!-- http://localhost:8080/v2/api-docs -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- it's format all API documentation organized -->
<!-- http://localhost:8080/swagger-ui.html -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<!-- for Security Support -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- for Tokens Support -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<!-- for Migration support $mvn flyway:migrate -->
<groupId>org.flywaydb</groupId>
<artifactId>flyway-maven-plugin</artifactId>
<configuration>
<url>jdbc:mysql://localhost:3306/rest_with_springboot?useTimezone=true&serverTimezone=UTC&useSSL=false</url>
<user>root</user>
<password>admin123</password>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
My POST request:
http://localhost:8080/auth/signin
With XML (application/xml):
<AccountCredentialsVO>
<username>leandro</username>
<password>admin123</password>
</AccountCredentialsVO>
With JSON (application/json):
{
"username":"leandro",
"password":"admin123"
}
And unfortunately with both requests I'm getting the same result of null username!

Spring boot 2.2.5 release Getting 404 not found error

I am trying to execute Spring boot application hosted on a tomcat server online. The issue is when I try to get, delete or post data, a user controller it generates this message.
{
"timestamp": "2021-01-24T06:45:42.144+00:00",
"status": 404,
"error": "Not Found",
"message": "",
"path": "/tool/api/v1/users"
}
the weird issue is that when I run the server locally http://localhost:8080/api/v1/users I get data
but when I try hosting the war file and hitting the endpoint http://31.134.12.356:9080/tool/api/v1/usersi end up with the error above.
My Users Controller
#RequestMapping("/api/v1")
#RestController
public class UserController {
#Autowired
private UserRepository userRepository;
#Autowired
private RoleRepository roleRepository;
#GetMapping("/users")
public Iterable<User> getAllUsers() {
return userRepository.findAll();
}
#GetMapping("/users/{id}")
public User getUserById(#PathVariable("id") String id) {
return userRepository.findById(id).get();
}
#GetMapping("/users/{username}")
public User getUserByUsername(#PathVariable("username") String username) {
return userRepository.findByUsername(username).get();
}
#PostMapping(value = "/users")
public ResponseEntity<Object> saveUser(#RequestBody SaveUserRequest userRequest) {
//save user details
User user = new User(userRequest.getUsername(),
userRequest.getDisplayName(), userRequest.getEmail(), userRequest.getIdentityProvider());
Set<String> strRoles = userRequest.getRole();
Set<Role> roles = new HashSet<>();
if (strRoles == null) {
Role userRole = roleRepository.findByName(ERole.ROLE_USER)
.orElseThrow(() -> new RuntimeException("Role is not found."));
roles.add(userRole);
} else {
strRoles.forEach(role -> {
switch (role) {
case "admin":
Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN)
.orElseThrow(() -> new RuntimeException("Role is not found."));
roles.add(adminRole);
break;
case "mod":
Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR)
.orElseThrow(() -> new RuntimeException("Role is not found."));
roles.add(modRole);
break;
default:
Role userRole = roleRepository.findByName(ERole.ROLE_USER)
.orElseThrow(() -> new RuntimeException("Role is not found."));
roles.add(userRole);
}
});
}
user.setRoles(roles);
user.setId(java.util.UUID.randomUUID().toString());
user.setLastLoggedOn(new Date());
userRepository.save(user);
return ResponseEntity.ok(user);
}
}
The weird issue is that I have other endpoints and they are working fine, the users rest api is the one not being found. I have added tool in the api as it is the name of the war file, I have multiple war files running on the tomcat.
ServletInitializer
public class ServletInitializer extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(MonitoringToolApplication.class);
}
}
Main class
#SpringBootApplication
#ComponentScan({ "com.example.tool.demo.controller"})
#EntityScan(basePackages = "com.example.tool.demo.model")
public class MonitoringToolApplication {
public static void main(String[] args) {
SpringApplication.run(MonitoringToolApplication.class, args);
}
}
my pom file
<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.2.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example.tool</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Example</name>
<description>example</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</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.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<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>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>8.2.2.jre8</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Application.properties file
#Example Tool connection string
spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.url=jdbc:sqlserver://localhost;databaseName=example_tools
spring.datasource.username=sa
spring.datasource.password= user2k!!__
## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.SQLServer2012Dialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql = true
Please help me out with the issue. Many thanks in advance.
When deploying the project on the server side, exclude the embedded tomcat in the pom.xml file
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>

Spring field required a bean of type that could not be found

I'm trying to make a Spring Boot Application with simple login page but when i try to use #Autowired with a interface that i created seems to be a problem. I read 7-8 similar questions but the answers that i find there was useless for me. #Autowired works fine when i use it on interface that expends JpaRepository.
my structure is:
My packages are on the same level as my Application file .
Here is my controller
#Controller
#RequestMapping(value = "/users")
public class LoginContoller {
#Autowired
UsersRepositoryCustom usersRepositoryCustom;
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginForm(){
return "login";
}
#RequestMapping(value = "/login", method = RequestMethod.POST)
public #ResponseBody
String verifyLogin(#RequestParam String name, #RequestParam String password) {
System.out.println("Controller: name: " + name + " pass " + password);
Users users=usersRepositoryCustom.loginUser(name, password);
if (users==null) {
System.out.println("login control user null");
return "login";
}
return "users/all";
}
}
Repository:
#Repository
public interface UsersRepositoryCustom {
Users loginUser(String name, String password);
}
I do not think it helps but here is the implementation
public abstract class UserImpl implements UsersRepositoryCustom {
#Autowired
UsersRepository usersRepository;
#Override
public Users loginUser(String name, String password) {
System.out.println("UserImpl: nume: " + name + " pass " + password);
Users user=usersRepository.findByUsername(name);
if (user != null && user.getPassword().equals(password)) {
System.out.println("User Login"+user.getId()+" "+user.getUsername());
return user;
}
return null;
}
}
Application.properties:
server.port=8080
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url= jdbc:mysql://localhost:3308/assignment-one-db
spring.datasource.username=root
spring.datasource.password=789456123
spring.jpa.hibernate.ddl-auto= update
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true
pom.xml
http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
<groupId>com.asg1</groupId>
<artifactId>asg1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>asg1</name>
<description>assignment1</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.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>10</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-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>
I try to use #EnableJpaRepositories, #EnableAutoConfiguration but it was useless
Here is the error:
Description:
Field usersRepositoryCustom in com.asg1.asg1.controllers.LoginContoller required a bean of type 'com.asg1.asg1.repository.UsersRepositoryCustom' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.asg1.asg1.repository.UsersRepositoryCustom' in your configuration.
Process finished with exit code 1

Field required a bean which could not be found in springboot

I am creating a basic spring boot REST API. My project has the following structure:
com.anonreporting.springboot
--- SpringBootAnonReporting.java , config.java
com.anonreporting.springboot.controller -- userController.java
com.anonreporting.springboot.domain -- User.java
com.anonreporting.springboot.service -- UserService.java UserServiceImpl.java
com.anonreporting.springboot.repository -- userRepository.java
SpringBootAnonReporting.java
#SpringBootApplication
public class SpringBootAnonReporting {
public static void main(String[] args) throws ParseException {
ApplicationContext applicationContext = SpringApplication.run(SpringBootAnonReporting.class, args);
for (String name : applicationContext.getBeanDefinitionNames()) {
System.out.println(name);
}
}
}
User.java is a POJO class.
UserController
#Controller
public class UserController {
#Autowired
UserService userService;
#RequestMapping(value="/users",method=RequestMethod.GET)
ResponseEntity<Iterable<User>> listAllUsers()
{
return new ResponseEntity<Iterable<User>>(userService.listAllUsers(),HttpStatus.OK);
}
#RequestMapping(value="/newuser",method=RequestMethod.POST)
ResponseEntity registerUser(User user)
{
userService.saveUser(user);
return new ResponseEntity(HttpStatus.CREATED);
}
#RequestMapping(value="/get",method=RequestMethod.GET)
ResponseEntity<String> tryGet()
{
System.out.println("hihihih");
return new ResponseEntity<String>("HI",HttpStatus.OK);
}
}
UserService:
#Service
public interface UserService {
Iterable<User> listAllUsers();
User getUserById(String id);
User saveUser(User user);
void deleteUser(String id);
}
UserServiceImpl:
#Service
public class UserServiceImpl implements UserService {
#Autowired
private UserRepository userRepository;
#Override
public Iterable<User> listAllUsers() {
// TODO Auto-generated method stub
return userRepository.findAll();
}
#Override
public User getUserById(String id) {
// TODO Auto-generated method stub
return userRepository.findOne(id);
}
#Override
public User saveUser(User user) {
// TODO Auto-generated method stub
return userRepository.save(user);
}
#Override
public void deleteUser(String id) {
// TODO Auto-generated method stub
userRepository.delete(id);
}
}
config.java
#Configurable
#Configuration
#EnableAutoConfiguration
#EnableTransactionManagement
public class Config {
public #Bean(destroyMethod = "close") AerospikeClient aerospikeClient() {
ClientPolicy policy = new ClientPolicy();
policy.failIfNotConnected = true;
policy.timeout = 2000;
return new AerospikeClient(policy, "172.28.128.3", 3000);
}
public #Bean AerospikeTemplate aerospikeTemplate() {
return new AerospikeTemplate(aerospikeClient(), "test");
}
}
UserRepository.java:
#Component
public interface UserRepository extends AerospikeRepository<User, String> {
}
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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>anonReporting</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>anonReporting</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.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-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.aerospike/aerospike-client -->
<dependency>
<groupId>com.aerospike</groupId>
<artifactId>aerospike-client</artifactId>
<version>4.1.9</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-commons-core -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons-core</artifactId>
<version>1.4.1.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-commons -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>2.0.9.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.aerospike/spring-data-aerospike -->
<dependency>
<groupId>com.aerospike</groupId>
<artifactId>spring-data-aerospike</artifactId>
<version>1.2.1.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-keyvalue -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-keyvalue</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-cli/commons-cli -->
<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
On running the code, the following error occurs:
***************************
APPLICATION FAILED TO START
***************************
Description:
Field userRepository in com.anonreporting.springboot.user.UserServiceImpl required a bean of type 'com.anonreporting.springboot.user.UserRepository' that could not be found.
Action:
Consider defining a bean of type 'com.anonreporting.springboot.user.UserRepository' in your configuration.
What I have tried:
All other packages are a sub package of com.anonreporting.springboot, so i don't have to use component scan for them (correct me if i am wrong).
I have tried with componentScan as well with no success.
Moving everything in same package does help, but i want to structure it in this way only. I am using areospike with spring boot.
I have tried changing versions of dependencies also.
Any suggestions would be really helpful. Thank you
As far as I see you have not created UserRepository.java. Spring can not Autowire something that does not exist so you can try creating it in a package that is convenient for you. It should look something like this
#Repository
public interface UserRepository extends JpaRepository<User, Long>{}
You need to change annotation in your UserRepository.class from #Component to #Repository as spring-data is scanning for #Repository annotations.
The problem was with pom.xml only. I just replaced my pom with the following and everything worked.
<?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>anonReporting</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>anonReporting</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.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-web</artifactId>
</dependency>
<dependency>
<groupId>com.aerospike</groupId>
<artifactId>spring-data-aerospike</artifactId>
<version>1.0.2.RELEASE</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>

How to get embedded Spring-Cloud-Server to read github properties file?

I am trying to embed a spring cloud server with git hub. Following this link right here.
Also following the following documentation
pom.xml
...
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</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-security</artifactId>-->
<!--</dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
...
</dependencies>
...
HelloWorldApplication.java
#SpringBootApplication
#EnableConfigServer
public class HelloWorldApplication {
public static void main(String[] args) {
SpringApplication.run(HelloWorldApplication.class, args);
}
}
HelloWorldController.java
#RestController
#RequestMapping("/hello")
#RefreshScope
public class HelloWorldController {
#Value("${prop1:default}") private String prop1;
#Value("${prop2:default}") private String prop2;
#RequestMapping(value = "/world", method = RequestMethod.GET)
public String getHelloWorld() {
return new StringBuilder()
.append("Message: ")
.append(prop1).append(" ")
.append(prop2).append("!")
.toString();
}
}
application.properties
server.port=8080
bootstrap.properties
spring.application.name=root-server
spring.cloud.config.server.bootstrap=true
spring.cloud.config.server.prefix=/config
spring.cloud.config.server.git.uri= www.githubrepo/config
spring.cloud.config.server.git.username = username
spring.cloud.config.server.git.password = password
Spring cloud GIT Repository file
${user.home}/Desktop/config/root-server.properties
prop1=Hello
prop2=World
Output
localhost:8080/hello/world
Message: default default!
It should be Message: Hello World!

Categories