When trying to use the api, I get this error:
"org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'authService' available".
How do I make the authservice be found by the app? I've gotten a similar error before, which I tried to fix by adding all the packages you see below in the Main class.
The Main class:
package com.lvwangbeta.poplar.api;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.lvwangbeta.poplar.action.PoplarActionServiceApplication;
import com.lvwangbeta.poplar.feed.PoplarFeedServiceApplication;
import com.lvwangbeta.poplar.tag.PoplarTagServiceApplication;
import com.lvwangbeta.poplar.user.PoplarUserServiceApplication;
import java.util.List;
#SpringBootApplication(scanBasePackages= {"com.lvwangbeta.poplar.common","com.lvwangbeta.poplar.common.intr","com.lvwangbeta.poplar.action",
"com.lvwangbeta.poplar.api.service",
"com.lvwangbeta.poplar.feed","com.lvwangbeta.poplar.tag",
"com.lvwangbeta.poplar.user", "com.lvwangbeta.poplar.api"})
//#ComponentScan({"com.lvwangbeta.poplar.common","com.lvwangbeta.poplar.user","com.lvwangbeta.poplar.feed.dao", "com.lvwangbeta.poplar.api"})
#ComponentScan({"com.lvwangbeta.poplar.action.dao.impl","com.lvwangbeta.poplar.feed.dao.impl"})
#MapperScan({"com.lvwangbeta.poplar.action.dao","com.lvwangbeta.poplar.feed.dao","com.lvwangbeta.poplar.tag.dao"})
public class PoplarApiApplication extends WebMvcConfigurerAdapter {
public static void main(String[] args) {
//Object[] sources = {PoplarApiApplication.class,PoplarTagServiceApplication.class};
//SpringApplication.run(sources, args);
System.out.println("Started");
SpringApplication.run(PoplarApiApplication.class, args);
//SpringApplication.run(PoplarTagServiceApplication.class, args);//I hope this works
//SpringApplication.run(PoplarActionServiceApplication.class, args);
//SpringApplication.run(PoplarFeedServiceApplication.class, args);
//SpringApplication.run(PoplarUserServiceApplication.class, args);
}
#Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
super.addArgumentResolvers(argumentResolvers);
argumentResolvers.add(new RequestAttributeArgumentResolver());
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
super.addInterceptors(registry);
registry.addInterceptor(new APIAccessAuthRequiredInterceptor())
.addPathPatterns("/api/v1/**")
.excludePathPatterns("/api/v1/user/login/**")
.excludePathPatterns("/api/v1/user/check/email/*")
.excludePathPatterns("/api/v1/user/register/**")
.excludePathPatterns("/api/v1/feed/of/user/**");
}
}
The AuthService class:
package com.lvwangbeta.poplar.api.service;
import com.lvwangbeta.poplar.common.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
#Service("authService")
public class AuthService {
#Autowired
private RedisTemplate<String, String> redisTemplate;
#Resource(name="redisTemplate")
private HashOperations<String, String, Object> mapOps;
public User getUserByToken(String token) {
return (User) mapOps.get("tokens:", token);
}
}
What am I missing? It's not registering even though the api link is there. I'm trying to combine many microservices to one, and so there's alot of packages.
include com.lvwangbeta.poplar.api.service in #ComponentScan
Like this :
#ComponentScan({"com.lvwangbeta.poplar.action.dao.impl","com.lvwangbeta.poplar.feed.dao.impl", "com.lvwangbeta.poplar.api.service"})
Suggestion :For simple applications avoid configuring the way above.
Keep your project structure as explained in this reference and #SpringBootApplication is enough.
https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#using-boot-locating-the-main-class
Related
I am trying to connect spring boot application with MySQL for that I have created a interface with name FilterDao which extend JpaRepository class. but whenever I try to make object of implemented class in Service I got this error "Consider defining a bean of type 'com.example.filter.FilterDao' in your configuration" as I am new to spring boot I don't understand this error.
FilterApplication.java
package com.example.filter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
#SpringBootApplication(exclude = {DataSourceAutoConfiguration.class })
public class FilterApplication {
public static void main(String[] args) {
SpringApplication.run(FilterApplication.class, args);
}
}
FilterDao.java
package com.example.filter;
import com.example.filter.Filter;
import org.springframework.context.annotation.Configuration;
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.query.FluentQuery;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
//#Configuration
public interface FilterDao extends JpaRepository<Filter, Integer> {
}
FilterService.java
package com.example.filter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
#Service
public class FilterService {
#Autowired
private FilterDao filterDao;
public List<Filter> getData() {
System.out.println("----------------------HERE-------------");
return filterDao.findAll();
}
}
FilterConnector.java
package com.example.filter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
#RestController
public class FilterConnector {
#Autowired
private FilterService filterService;
#GetMapping("/home")
public List<Filter> home()
{
return this.filterService.getData();
}
}
Project Structure
Annotate FilterDao with #Repository
Seems spring has not created bean for FilterDao repository and you are trying to use that`
#Autowired
private FilterDao filterDao;`
There might different reasons for this exception. Please try the below solution.
Use #EnableJpaRepositories(basePackages = "com.example.filter") with your FilterApplication class.
Use #ComponentScan(basePackages = "com.example.*") with FilterApplication class
Use #Repoitory annotation with FilterDao interface.
Hope this helps. For more details check the below tutorial.
https://javatute.com/jpa/consider-defining-a-bean-of-type-in-your-configuration/
Have SpringBoot Java app with different classes. I am not able to inject the dependencies and initialize/access the object of one class into another . Have seen the spring doc and used the annotations (#component,#Autowired etc. ), still there is an issue.
following are the classes.
Main Class ()
package com.test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
#SpringBootApplication
public class CostmanagementApplication {
public static void main(String[] args) {
SpringApplication.run(CostmanagementApplication.class, args);
}
}
Controller class
package com.test;
import javax.swing.text.rtf.RTFEditorKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
#Component
#Controller
public class HighChartsController {
#Autowired
private RequestToken rt;
#GetMapping("/costdata")
public static String customerForm(Model model) {
//here not able to access the getToken() method
model.addAttribute("costdata", new CostDataModel());
return "costdata";
}
}
RequestToken Class
package com.test;
import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.stream.Collectors;
import org.json.JSONObject;
import org.springframework.stereotype.Component;
#Component
public class RequestToken {
public String getToken() throws IOException, InterruptedException {
// TODO Auto-generated method stub
// code to get the token
return token;
}
}
now eventhough , I have all annotation in place , not getting why the getToken() method is not accessible in controller class using rt object. please suggest
Okay, let's go in order.
First of all, all the annotations #Service, #Controller and #Repository are specifications from #Component, so you don't need to specify #Component and #Controller in your HighChartsController.
Actually, if you check what the annotation #Controller definition is, you'll find this:
#Component
public #interface Controller {
...
}
Secondly, I don't really know what do you mean with that you aren't able to access the getToken() method, but as you wrote it seems you tried to access to that method as an static method.
You're injecting the object, so you use the methods of the objects like in plain Java: rt.getToken(). The only difference is that the RequestToken object will be already initialized at the moment you call it.
package com.test;
import javax.swing.text.rtf.RTFEditorKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
#Controller
public class HighChartsController {
#Autowired
private RequestToken rt;
#GetMapping("/costdata")
public static String customerForm(Model model) {
String token = rt.getToken();
...
model.addAttribute("costdata", new CostDataModel());
return "costdata";
}
}
I have a Data Loader Class which is suppose to load data once the app starts.
My Error -
Could not autowire. No beans of 'OwnerService' Found.
However, my ownerService class is annotated as I have shown below -
This is the class whose supposed to do that -
DataLoader
import model.Owner;
import model.Vet;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import services.OwnerService;
import services.VetService;
import services.map.OwnerServiceMap;
import services.map.VetServiceMap;
#Component
public class DataLoader implements CommandLineRunner {
private final OwnerService ownerService;
private final VetService vetService;
public DataLoader(OwnerService ownerService, VetService vetService) {
this.ownerService = ownerService;
this.vetService = vetService;
}
OwnerServiceMap
package services.map;
import model.Owner;
import org.springframework.stereotype.Service;
import services.OwnerService;
import java.util.Set;
#Service
public class OwnerServiceMap extends AbstractMapService<Owner,Long> implements OwnerService
{//some code here}
The vetService is the same as ownerService.
My applcation class -
package petclinic;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class PetclinicApplication {
public static void main(String[] args) {
SpringApplication.run(PetclinicApplication.class, args);
}
}
Maybe I have hierarchy problems, as the application class doesn't search for beans in enough places in the project?
Thank you!
I just started learning spring batch with no prior experience of Spring batch.
I downloaded a template from start.spring.io and selected following
After this I imported the project in IntelliJ IDE and made following changes
Added a job configuration class:
package io.spring.helloworld.configuration;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.StepContribution;
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.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration //For spring configuration
#EnableBatchProcessing //bootstrap all the infra needed to run spring batch
public class jobConfiguration {
#Autowired
private JobBuilderFactory jobBuilderFactory;
#Autowired
private StepBuilderFactory stepBuilderFactory;
#Bean
public Step step1() {
return stepBuilderFactory.get("step1")
.tasklet(new Tasklet() {
#Override
public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
System.out.println("Hello World");
return RepeatStatus.FINISHED;
}
}).build();
}
#Bean
public Job HelloWorld() {
return jobBuilderFactory.get("HelloWorldJob")
.start(step1())
.build();
}
}
and this is how my entry class looks
package io.spring.helloworld;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
#SpringBootApplication
public class HelloWorldApplication {
public static void main(String[] args) {
SpringApplication.run(HelloWorldApplication.class, args);
System.exit(0);
}
}
I have not touched or modified any class\configuration. But when i run the app, I get following message:
Description:
Cannot determine embedded database driver class for database type NONE
Action:
If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
What Can i do to fix this error?
To resolve this error there are two methods:
Method 1:
Try adding below annotation:
#EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
example:
#SpringBootApplication
#EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class HelloWorldApplication {
-----
}
Method 2:
you can add the below line in application.properties file
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
Can you please provide me with an example of primitive type dependency injection in spring boot. I have tried once but TestConfiguration which is my custom bean definition class does not detect or does not recognize by spring boot application.
here is my code,
//Engine class
package com.test2.projectTest;
import org.springframework.stereotype.Component;
#Component
public class Engine {
private String msg;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
//Test Configuration
package com.test2.projectTest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
public class TestConfiguration {
#Bean("engine")
public Engine engine(){
Engine engine = new Engine();
engine.setMsg("Message is injected");
return engine;
}
}
//spring main application
package com.test2.projectTest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
public class ProjectTestApplication {
public static void main(String[] args) {
SpringApplication.run(ProjectTestApplication.class, args);
}
}
//JUnit Test
package com.test2.projectTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;
#RunWith(SpringRunner.class)
#SpringBootTest
public class ProjectTestApplicationTests {
#Test
public void contextLoads() {
ApplicationContext apc = new
AnnotationConfigApplicationContext(TestConfiguration.class);
Engine e = (Engine) apc.getBean("engine");
e.getMsg();
}
}
// Output - org.springframework.beans.factory.NoSuchBeanDefinitionException:
No bean named 'engine' available
Please suggest any solution to above issue
Add #componentscan annotation in main class and provide engine class package and it should work