Here is my class
#Configuration
class MongoDBConfig {
private Logger logger = LoggingFactory.getLogger(getClass());
#Bean
#Scope(value = "singleton", proxyMode = ScopedProxyMode.INTERFACES)
public MongoClient mongoClient() throws UnknownHostException {
logger.error("In Dev mode:");
return new MongoClient("fctest");
}
#Bean
public DB mongoDB() throws UnknownHostException{
try {
return mongoClient().getDB(FCProperties.MONGO_DB_NAME);
}catch (UnknownHostException ue){
logger.error("Error occurred: "+ue.getMessage());
throw ue;
}
}
}
And here is how I'm using it -
public class UserRepository extends BaseRepository {
#Autowired
public UserRepository(DB mongoDB) {
super("users", mongoDB);
}
}
I'm getting the following error
Error creating bean with name 'mongoDB' defined in class path resource [com/fctest/mongo/config/MongoDBConfig.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public com.mongodb.DB com.fctest.mongo.config.MongoDBConfig.mongoDB() throws java.net.UnknownHostException] threw exception; nested exception is java.lang.ClassCastException: com.sun.proxy.$Proxy13 cannot be cast to com.mongodb.MongoClient
Related
How can I inject the following application.properties into a Map field?
my.server.url=localhost
my.server.port=8080
my.server.timeout=10000
What is wrong with the following class?
#Service
#ConfigurationProperties("my")
public class MyService {
private Map<String, String> server;
public void setServer(Map<String, String> server) { this.server = server; }
public MyService(WebClient.Builder builder) {
this.builder = builder.uri(server.get("url")).build();
}
}
Result:
Bean instantiation via constructor failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [MyService]: Constructor threw exception; nested exception
is java.lang.NullPointerException
create a bean as following in the configuration class :
#Bean(name = "appProperties")
public static PropertiesFactoryBean mapper() {
PropertiesFactoryBean bean = new PropertiesFactoryBean();
bean.setLocation(new ClassPathResource("application.properties"));
return bean;
}
And then inject the values in it as map as follows in to the desired class :
#Resource(name = "appProperties")
private Map<String, String> properties;
Hi i'm new to spring boot and trying implement the security to my rest apis.
i'm using spring boot 2.0.7.release
i have configures my WebSecurityConfig as following
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Resource(name = "userService")
private UserDetailsService userDetailsService;
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(encoder());
}
#Bean
public JwtAuthenticationFilter authenticationTokenFilterBean() throws Exception {
return new JwtAuthenticationFilter();
}
#Bean
public PasswordEncoder encoder(){
PasswordEncoder encoder = new CustomPasswordEncoder();
return encoder;
}
....
}
I have add the resource name so that i can point the to custom userDetailsService.
I have tried configuring authenticationManager Bean by came and pointing the bean by Qualifier authenticationManager bean still it the error remains same.
my pom.xml looks like for security
......
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
......
and my implemented UserServiceImpl is
#Service(value = "userService")
public class UserServiceImpl implements UserService, UserDetailsService {
#Autowired
private UserDAOService userDao;
#Autowired
private AuthenticationManager authenticationManager;
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userDao.findByUsername(username);
if(user == null){
throw new UsernameNotFoundException("Invalid username or password.");
}
return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), getAuthority());
}
#Override
public String login(LoginUser user) {
// valid user if it exits then do the following
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword()));
//generate the token and do other process.
}
following are the error logs. i have provided only mail errors
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'webSecurityConfig': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService': Unsatisfied dependency expressed through field 'authenticationManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authenticationManager' defined in class path resource [com/saikrishna/security/config/WebSecurityConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.authentication.AuthenticationManager]: Circular reference involving containing bean 'webSecurityConfig' - consider declaring the factory method as static for independence from its containing instance. Factory method 'authenticationManagerBean' threw exception; nested exception is java.lang.IllegalArgumentException: delegateBuilder cannot be null
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService': Unsatisfied dependency expressed through field 'authenticationManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authenticationManager' defined in class path resource [com/saikrishna/security/config/WebSecurityConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.authentication.AuthenticationManager]: Circular reference involving containing bean 'webSecurityConfig' - consider declaring the factory method as static for independence from its containing instance. Factory method 'authenticationManagerBean' threw exception; nested exception is java.lang.IllegalArgumentException: delegateBuilder cannot be null
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authenticationManager' defined in class path resource [com/saikrishna/security/config/WebSecurityConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.authentication.AuthenticationManager]: Circular reference involving containing bean 'webSecurityConfig' - consider declaring the factory method as static for independence from its containing instance. Factory method 'authenticationManagerBean' threw exception; nested exception is java.lang.IllegalArgumentException: delegateBuilder cannot be null
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.authentication.AuthenticationManager]: Circular reference involving containing bean 'webSecurityConfig' - consider declaring the factory method as static for independence from its containing instance. Factory method 'authenticationManagerBean' threw exception; nested exception is java.lang.IllegalArgumentException: delegateBuilder cannot be null
Caused by: java.lang.IllegalArgumentException: delegateBuilder cannot be null
at org.springframework.util.Assert.notNull(Assert.java:193) ~[spring-core-5.0.11.RELEASE.jar:5.0.11.RELEASE]
In order to help you better, it is better if you indicate which reference you are following to implement JWT mechansim.
Conceptually, this part of the source code is wrong:
#Override
public String login(LoginUser user) {
// valid user if it exits then do the following
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword()));
//generate the token and do other process.
}
See if the modifications below can help you
1) Consider using Java Config to declare your beans, in a seperate Configuration class
#Configuration
public class ServiceConfig{
#Bean
protected UserDAOService daoService()
{
return new UserDAOServiceImpl();
}
#Bean
protected UserDetailsService userDetailService( UserDAOService dao )
{
return new UserServiceImpl( dao );
}
#Bean
public PasswordEncoder encoder(){
PasswordEncoder encoder = new CustomPasswordEncoder();
return encoder;
}
#Bean
public JwtAuthenticationFilter authenticationTokenFilterBean() throws Exception{ {
return new JwtAuthenticationFilter();
}
}
2) Modification to your WebSecurityConfig
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserDetailsService userDetailsService;
#Autowired
private PasswordEncoder passwordEncoder;
#Override
protected void configure( AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService( userDetailsService ).passwordEncoder( passwordEncoder );
}
}
I need use a bean inject with #Component #FeignClient(name = "xxx") when my spring boot application initializing, but it always throws exception like this:
20180706 10:18:40,043 WARN [main]
[org.springframework.context.annotation.AnnotationConfigApplicationContext]
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'feignContract' defined in org.springframework.cloud.netflix.feign.FeignClientsConfiguration: Unsatisfied dependency expressed through method 'feignContract' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'feignConversionService' defined in org.springframework.cloud.netflix.feign.FeignClientsConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.format.support.FormattingConversionService]: Factory method 'feignConversionService' threw exception; nested exception is java.lang.StackOverflowError
my feignClient code:
#Component
#FeignClient(name = "domain-account")
public interface IDomainService {
#RequestMapping(value = "/userInfos", method = RequestMethod.GET)
public String getUserInfos(#QueryMap Map<String, Object> condition);
}
ApplicationListenner code:
public class GlobalInit implements ApplicationListener<ContextRefreshedEvent> {
#Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
System.out.println("======== GlobalInit ========");
IDomainService domainService = contextRefreshedEvent.getApplicationContext().getBean(IDomainService.class);
System.out.println("*********************" + domainService);
GlobalInitManager.getInstance().doInit();
}
}
It's not entirely clear for me what you try to do with the GlobalInit but the 'standard' way of designing your Feign client in Spring Boot would the following:
#SpringBootApplication
#EnableFeignClients
#EnableHypermediaSupport(type = EnableHypermediaSupport.HypermediaType.HAL)
#EnableCaching
public class MyHelloWorldApplication {
public static void main(String[] args) {
SpringApplication.run(MyHelloWorldApplication.class, args);
}
}
#Component
public class HelloWorldServiceImpl implements HelloWorldService {
#Autowired
private IDomainService iDomainService ;
public void myMethod() {
String userinfo = iDomainService.getUserInfos(...);
}
}
Hopefully this helps.
All the best,
Wim
I created an simple application without web.xml and spring-servlet.xml config file. I just config in Java code.
This is the project structure:
Project structure
This is my main class:
public class TripMapServer {
private static final int DEFAULT_PORT = 8080;
private static final String CONTEXT_PATH = "/";
private static final String MAPPING_URL = "/";
private static final String CONFIG_LOCATION = "com.biendltb.config";
private static final String DEFAULT_PROFILE = "dev";
public static void main(String[] args) throws Exception {
new TripMapServer().startJetty(getPortFromArgs(args));
}
private static int getPortFromArgs(String[] args) {
if (args.length > 0) {
try {
return Integer.valueOf(args[0]);
} catch (NumberFormatException ignore) {
}
}
return DEFAULT_PORT;
}
private void startJetty(int port) throws Exception {
Server server = new Server(port);
server.setHandler(getServletContextHandler(getContext()));
server.start();
server.join();
}
private static ServletContextHandler getServletContextHandler(WebApplicationContext context) throws IOException {
ServletContextHandler contextHandler = new ServletContextHandler();
contextHandler.setErrorHandler(null);
contextHandler.setContextPath(CONTEXT_PATH);
contextHandler.addServlet(new ServletHolder(new DispatcherServlet(context)), MAPPING_URL);
contextHandler.addEventListener(new ContextLoaderListener(context));
contextHandler.setResourceBase(new ClassPathResource("webapp").getURI().toString());
return contextHandler;
}
private static WebApplicationContext getContext() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setConfigLocation(CONFIG_LOCATION);
context.getEnvironment().setDefaultProfiles(DEFAULT_PROFILE);
return context;
}
}
I created another class named WebConfig.java to set the config for spring-servlet:
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = {"com.biendltb.controller"})
public class WebConfig extends WebMvcConfigurerAdapter{
private static final Charset UTF8 = Charset.forName("UTF-8");
#Autowired
public Environment env;
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(stringConverter());
}
private StringHttpMessageConverter stringConverter() {
StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
stringConverter.setSupportedMediaTypes(Arrays.asList(new MediaType("text", "plain", UTF8)));
return stringConverter;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/assets/**").addResourceLocations("classpath:/src/main/resources/").setCachePeriod(Integer.MAX_VALUE);
registry.addResourceHandler("/js/**").addResourceLocations("/js/").setCachePeriod(Integer.MAX_VALUE);
registry.addResourceHandler("/css/**").addResourceLocations("/css/").setCachePeriod(Integer.MAX_VALUE);
registry.addResourceHandler("/img/**").addResourceLocations("/img/").setCachePeriod(Integer.MAX_VALUE);
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Bean
public InternalResourceViewResolver getInternalResourceViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/src/main/resources/pages/");
resolver.setSuffix(".jsp");
return resolver;
}
}
Error happened when I add the configureDefaultServletHandling function.
[org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'defaultServletHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException: Unable to locate the default servlet for serving static content. Please set the 'defaultServletName' property explicitly.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultServletHandlerMapping' defined in class path resource [org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'defaultServletHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException: Unable to locate the default servlet for serving static content. Please set the 'defaultServletName' property explicitly.
It cannot find the default name of servlet. Normally, the default name of servlet will be "default".
I think maybe I should set the servlet name to solve this problem.
Do you have any idea to solve this problem?
Sorry about the code format not display correctly. Appreciated you support. Thank you very much.
I already found how to set the name for Spring servlet by java code:
contextHandler.addServlet(new ServletHolder("default", new DispatcherServlet(context)), MAPPING_URL);
But I met another issue, that is:
java.lang.NoClassDefFoundError: Could not initialize class org.springframework.web.util.NestedServletException
I try to google, many people faced with NoClassDefFoundError but no one met the issue org.springframework.web.util.NestedServletException.
I checked again to make sure all dependency were added.
Maybe I should post another question for that issue :(
This is the first time I am using Spring batch and I have an exception :
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'stepScope' defined in class path resource [org/springframework/batch/core/configuration/annotation/StepScopeConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.batch.core.scope.StepScope org.springframework.batch.core.configuration.annotation.StepScopeConfiguration.stepScope()] threw exception; nested exception is java.lang.NoSuchMethodError: org.springframework.batch.core.scope.StepScope.setAutoProxy(Z)V
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:581)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1031)
....
Caused by: java.lang.NoSuchMethodError: org.springframework.batch.core.scope.StepScope.setAutoProxy(Z)V
at org.springframework.batch.core.configuration.annotation.StepScopeConfiguration.stepScope(AbstractBatchConfiguration.java:130)
I don't know how to solve this error. I am using a Java configuration to define the job, the step, the reader, the processor and the writer :
public class SpringBatchTestJobConfig extends PersistenceSpringConfig {
#Autowired
private JobBuilderFactory jobBuilders;
#Autowired
private StepBuilderFactory stepBuilders;
#Bean
#StepScope
public FlatFileItemReader<EntiteJuridique> cvsReader(#Value("#{jobParameters[input.file]}") String input)
{
log.info("cvsReader");
FlatFileItemReader<EntiteJuridique> flatFileReader = new FlatFileItemReader<EntiteJuridique>();
flatFileReader.setLineMapper(lineMapper());
flatFileReader.setResource(new ClassPathResource(input));
return flatFileReader;
}
#Bean
public ItemWriter<EntiteJuridiqueJPA> writer()
{
log.info("writer");
JpaItemWriter<EntiteJuridiqueJPA> jpaWriter = new JpaItemWriter<EntiteJuridiqueJPA>();
try
{
jpaWriter.setEntityManagerFactory(entityManagerFactory().nativeEntityManagerFactory);
}
catch (Exception exception)
{
log.debug(exception);
}
return jpaWriter;
}
#Bean
public Job dataInitializer()
{
return jobBuilders.get("dataInitializer").start(step()).build();
}
#Bean
public Step step()
{
return stepBuilders.get("step").<EntiteJuridique, EntiteJuridiqueJPA> chunk(1).reader(cvsReader(null)).processor(processor())
.writer(writer()).build();
}
Any clues to how this problem?
EDIT : I am using
spring-core 3.2.2.RELEASE
spring-batch 2.2.0.RELEASE
spring-batch-infrastructure 2.2.0.RELEASE
spring-test 3.2.2.RELEASE
I got this same error, the solution for me was removing the version from my dependency and it worked fine.
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-core</artifactId>
</dependency>