Error #Autowired an interface with another project - spring

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MiParteTrabajoDao': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.mydomain.repository.produccion.ParteTrabajoRepository com.mydomain.dao.produccion.ParteTrabajoDaoExample.parteRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.mydomain.repository.produccion.ParteTrabajoRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#javax.inject.Inject()}
package com.mydomain.repository;
import java.io.Serializable;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.NoRepositoryBean;
#NoRepositoryBean
public interface CrudRepository<T, ID extends Serializable> extends JpaRepository<T, ID> {
#Override
<S extends T> S save(S entity);
#Override
T findOne(ID primaryKey);
#Override
List<T> findAll();
#Override
long count();
#Override
void delete(T entity);
#Override
boolean exists(ID primaryKey);
}
and
package com.mydomain.repository.produccion;
public interface ParteTrabajoRepository extends CrudRepository<PParteTrabajo, PParteTrabajoPK> {
#Query(value = "select u from PParteTrabajo u where u.idParteTrabajo like %?1", nativeQuery = true)
public PParteTrabajo findByIdParteTrabajo(int idParteTrabajo);
}
and
package com.mydomain.dao.produccion;
public interface ParteTrabajoDaoI {
public List<PParteTrabajo> findAll();
}
and
package com.mydomain.dao.produccion;
#Repository("MiParteTrabajoDao")
public class ParteTrabajoDaoExample implements ParteTrabajoDaoI {
#Autowired
private ParteTrabajoRepository parteRepository;
#Override
public List<PParteTrabajo> findAll() {
final List<PParteTrabajo> lista = parteRepository.findAll();
return null;
}
}
and
package com.mydomain.services.produccion;
import com.mydomain.entities.produccion.PParteTrabajo;
import com.mydomain.util.dao.DaoException;
import com.mydomain.util.exception.FindException;
public interface ParteTrabajoServiceI<T> {
public T iniciarParteTrabajo(int idMaquina, int idEstacion, int idOperario, int idTrabajo, int idOrden)
throws FindException;
public PParteTrabajo iniciarFinalizarParteTrabajo(int idMaquina, int idEstacion, int idOperario, int idTrabajo,
int idOrden) throws FindException, DaoException;
public T iniciarParteTrabajoMaquinaTrabajoUnico(int idMaquina, int idOperario, int idOrden) throws FindException,
DaoException;
public PParteTrabajo finalizarParteTrabajo(T parteTrabajoIniciado, BigDecimal cantidad) throws DaoException,
FindException;
public List<PParteTrabajo> finalizarPartesTrabajosIniciados(int idMaquina, int idOperario) throws FindException,
DaoException;
public List<T> getPartesTrabajoIniciados(int idMaquina, int idOperario) throws FindException;
public List<T> getPartesTrabajoIniciados(int idMaquina) throws FindException;
public List<T> findAll() throws FindException;
}
and
package com.mydomain.services.produccion;
import com.mydomain.dao.produccion.ParteTrabajoDaoI;
import com.mydomain.entities.produccion.PParteTrabajo;
import com.mydomain.util.dao.DaoException;
import com.mydomain.util.exception.FindException;
#Service("parteTrabajoServicePrueba")
public class ParteTrabajoServiceExample implements
ParteTrabajoServiceI<ParteTrabajoServiceExample.ParteTrabajoIniciado> {
#Autowired
#Qualifier("MiParteTrabajoDao")
private ParteTrabajoDaoI parteTrabajoDaoI;
#Override
public List<ParteTrabajoIniciado> getPartesTrabajoIniciados(final int idMaquina, final int idOperario) {
return null;
}
public class ParteTrabajoIniciado {
private final PParteTrabajo parte;
private ParteTrabajoIniciado(final PParteTrabajo parteTrabajo) {
parte = parteTrabajo;
}
public int getIdOrdenProduccion() {
return parte.getIdOrdenProduccion();
}
}
....
}
and
package com.mydomain.iweb;
#SpringBootApplication
#Configuration
#Import(com.mydomain.services.ServicesBeanConfig.class)
#EnableTransactionManagement
#EnableAutoConfiguration
#PropertySource("file:etc/application.properties")
#EnableJpaRepositories("com.mydomain.repository,com.mydomain.dao")
public class Application {
private static final Logger LOG = LoggerFactory.getLogger(Application.class.getName());
#Value("${spring.datasource.jndi-name}")
private String jndiResourceName;
#Value("${spring.datasource.name}")
private String jdbcName;
#Value("${spring.datasource.driver-class-name}")
private String jdbcDriverClassName;
#Value("${spring.datasource.url}")
private String jdbcUrl;
#Inject
ApplicationContext ctx;
public static void main(final String[] args) {
SpringApplication.run(Application.class, args);
}
.....
}

The value for EnableJpaRepositories is wrong.
The value is an array, so it should be
#EnableJpaRepositories(value ={"com.mydomain.repository","com.mydomain.dao"})
The way you declared it spring would try to scan only one package with the name
"com.mydomain.repository,com.mydomain.dao"
which for sure is not what you want.

You may have missed the bean implementing the ParteTrabajoRepository interface.
com.mydomain.repository.produccion.ParteTrabajoRepository is just an interface but it needs a concrete implementation in order for it to be injected with #Autowired

Related

java.lang.IllegalArgumentException: Not a managed type: class while initiating repository bean

Hi I am trying to load some database values at start time of spring boot application. I have autowired service, and in service i have autowired Dao. Below is the error.
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'validationExpressionService': Unsatisfied dependency expressed through field 'validationExpressionDao'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'IValidationExpressionDao': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.ril.nfg.dao.bean.ValidationExpression
I have added #EnitityScan #EnableJPARepository
FYI, Primary key in the case in String, hope that is ok.
Entity
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* The Class ValidationExpression.
*/
package com.ril.nfg.dao.bean;
#Entity
#Table(name = "VALIDATION_EXPRESSION")
public class ValidationExpression implements Serializable {
private static final long serialVersionUID = 9096950800262493651L;
private String validationId;
private String expression;
private String createdBy;
private Date createdOn;
private String description;
private String responseCode;
#Id
#Column(name = "VALIDATION_ID", nullable = false, length = 100)
public String getValidationId() {
return validationId;
}
public void setValidationId(String validationId) {
this.validationId = validationId;
}
#Column(name = "EXPRESSION", nullable = false, length = 200)
public String getExpression() {
return expression;
}
public void setExpression(String expression) {
this.expression = expression;
}
//remaining getters and setters
}
Repository
package com.ril.nfg.dao.repos;
import com.ril.nfg.dao.bean.ValidationExpression;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
/**
* The Interface IValidationExpressionDao.
*/
#Repository
public interface IValidationExpressionDao extends JpaRepository<ValidationExpression, String> {
}
Service
import java.util.List;
#Service
public class ValidationExpressionService {
#Autowired
IValidationExpressionDao validationExpressionDao;
public List<ValidationExpression> getAll() {
return validationExpressionDao.findAll();
}
}
Class with #Autwired Service
public class CacheModuleParam implements ApplicationContextAware{
private static List<ValidationExpression> validationExpressionList = null;
#Autowired
ValidationExpressionService validationExpressionService;
#Override
public void setApplicationContext(final ApplicationContext appContext) throws BeansException {
validationExpressionList = validationExpressionService.getAll();
}
}
Application Class
#ComponentScan(basePackages = {"com.ril.nfg"})
#EnableWebMvc
#EnableAutoConfiguration
#SpringBootApplication//(exclude={DataSourceAutoConfiguration.class})
#EnableJpaRepositories(basePackages="com.ril.nfg.dao.repos",entityManagerFactoryRef="oracleEntityManagerFactory")
//#EntityScan(basePackages = "com.ril.nfg.dao.bean")
public class NFGApplication {
public static void main(String[] args) {
SpringApplication.run(NFGApplication.class, args);
}
}
All solutions on internet focuses on #EntityScan. Please help me understand what is wrong with this code. Thanks in advance
Why do you have all this configuration? Simply put our application in the package tree one level above all the other classes and you can go with a class like this:
#SpringBootApplication
public class NFGApplication {
public static void main(String[] args) {
SpringApplication.run(NFGApplication.class, args);
}
}
Packages:
com.ril.nfg <- here you put NFGApplication
And all other classes in subpackages of com.ril.nfg
And then everything will work!

Couldn't find PersistentEntity for type class when using #EnableMongoAuditing

I am getting "Couldn't find PersistentEntity for type class" error when I am using #EnableMongoAuditing features along with MongoRepository.
This happens when I save a document when collection isn't already present in database.
I tried whatever is mentioned in:
https://github.com/spring-projects/spring-boot/issues/12023
https://jira.spring.io/browse/DATAMONGO-1999
Spring boot mongodb auditing error
but nothing is working.
Mentioned things are:
Extend MongoConfig by AbstractMongoConfiguration and override all methods.
Here is my code which reproduced the same error:
MongoConfig class
#Configuration
public class MongoConfig extends AbstractMongoConfiguration {
#Value("${spring.data.mongodb.host}")
private String mongoHost;
#Value("${spring.data.mongodb.port}")
private String mongoPort;
#Value("${spring.data.mongodb.database}")
private String mongoDB;
#Override
public MongoDbFactory mongoDbFactory() {
return new SimpleMongoDbFactory(new MongoClient(mongoHost + ":" + mongoPort), mongoDB);
}
#Override
public MongoClient mongoClient() {
return new MongoClient(mongoHost, Integer.parseInt(mongoPort));
}
#Override
public MongoTemplate mongoTemplate() {
return new MongoTemplate(mongoDbFactory());
}
#Override
public MappingMongoConverter mappingMongoConverter() {
return new MappingMongoConverter(new DefaultDbRefResolver(mongoDbFactory()), new MongoMappingContext());
}
#Override
protected String getDatabaseName() {
return mongoDB;
}
}
Person Collection class
#Document
public class Person {
#Id
private String id;
private String name;
#CreatedDate
private LocalDateTime createdAt;
#LastModifiedDate
private LocalDateTime lastModified;
// Getter Setters Constructors omitted for brevity
}
Main Application class
#EnableMongoAuditing
#EnableMongoRepositories ({"com.example.*", "org.apache.*"})
#SpringBootApplication
#ComponentScan({"com.example.*", "org.apache.*"})
public class DemoApplication implements CommandLineRunner {
#Autowired
PersonRepository personRepository;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
Person p1 = new Person("1", "prakhar");
personRepository.save(p1);
}
}
Expected Result is Person entity should be saved in database.
Actual Result is "Couldn't find PersistentEntity for type class Person" error
Looks like you ran into https://github.com/spring-projects/spring-boot/issues/12023
Extending AbstractMongoConfiguration will switch off Spring Boot's auto-configuration of various Mongo components and also customises the base packages that are used to scan for mappings. I would recommend that you don't use it in Spring Boot.
Update
I managed to get the example running with the configuration as simple as
#Configuration
public class MongoConfig {
#Value("${spring.data.mongodb.host}")
private String mongoHost;
#Value("${spring.data.mongodb.port}")
private String mongoPort;
#Value("${spring.data.mongodb.database}")
private String mongoDB;
#Bean
public MongoDbFactory mongoDbFactory() {
return new SimpleMongoDbFactory(new MongoClient(mongoHost + ":" + mongoPort), mongoDB);
}
#Bean
public MongoClient mongoClient() {
return new MongoClient(mongoHost, Integer.parseInt(mongoPort));
}
}
and the app class
#EnableMongoAuditing
#SpringBootApplication
public class DemoApplication implements CommandLineRunner {
#Autowired
PersonRepository personRepository;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
Thread.sleep(2000);
Person p1 = new Person("1", "prakhar");
personRepository.save(p1);
}
}
Notice that I followed my own advice and did't inherit from AbstractMongoConfiguration
Explanation
The problem lies in the initialization of
#Bean
public MappingMongoConverter mappingMongoConverter() {
return new MappingMongoConverter(new DefaultDbRefResolver(mongoDbFactory()), new MongoMappingContext());
}
You simply call MongoMappingContext constructor, without calling setInitialEntitySet. Compare that with MongoDataConfiguration auto-configuration class.
#Bean
#ConditionalOnMissingBean
public MongoMappingContext mongoMappingContext(MongoCustomConversions conversions)
throws ClassNotFoundException {
MongoMappingContext context = new MongoMappingContext();
context.setInitialEntitySet(new EntityScanner(this.applicationContext)
.scan(Document.class, Persistent.class));
Class<?> strategyClass = this.properties.getFieldNamingStrategy();
if (strategyClass != null) {
context.setFieldNamingStrategy(
(FieldNamingStrategy) BeanUtils.instantiateClass(strategyClass));
}
context.setSimpleTypeHolder(conversions.getSimpleTypeHolder());
return context;
}
Even worse, you don't register MongoMappingContext as a managed bean.
Due to this fact, auto-configuration class is still created. This leads to a race condition, I tried to run the original code and could easily reproduce the error, but with a breakpoint in AbstractMappingContext.addPersistentEntity the test always passed.
For me I resolved this issue by adding following method in MongoConfig if your class extends from AbstractMongoConfiguration
#Override
protected String getMappingBasePackage() {
return "com.companyName.modulename"
}
If MongoConfig extends from MongoConfigurationSupport then add below method
#Override
protected Collection<String> getMappingBasePackages() {
return Arrays.asList("com.companyName.module1","com.companyName.module2");
}
Note that in later case I can specify multiple package names as base packages.

Spring Bean Factory Configuration passing input parameter

I'm trying to create a BeanFactory called TaskBeanFactory that I can Autowire into another prototype class that's running on a thread. I want a different instance of a bean returned by the Factory based on a taskName that i want to pass into it but when i start the application i get a null pointer exception because the taskName is null. I had a look at this article but i'm confused about how I should configure the Factory and then pass in the taskName.
The Factory:
import org.springframework.beans.factory.config.AbstractFactoryBean;
import org.springframework.stereotype.Component;
#Data
#Component
#NoArgsConstructor
public class TaskBeanFactory extends AbstractFactoryBean<GenericTask>{
private TaskNameEnum taskName;
public TaskBeanFactory(TaskNameEnum taskName) {
setSingleton(false);
}
#Override
public Class<?> getObjectType() {
return GenericTask.class;
}
#Override
protected GenericTask createInstance() throws Exception {
switch (taskName) {
case FILE_OPERATION:
return new FileTask();
case DATA_OPERATION:
return new DataTask();
default:
return new GenericTask();
}
}
}
The classes used by the Factory:
#Data
public class GenericTask {
private String idTask;
public void executeTask(Work work) {};
}
#Component
#Scope(value="prototype")
public class FileTask extends GenericTask {
#Override
public void executeTask(Work work) {
//some processing
}
}
#Component
#Scope(value="prototype")
public class DataTask extends GenericTask {
#Override
public void executeTask(Work work) {
//some processing
}
}
and the thread that's calling the Factory:
#Slf4j
#Data
#Scope("prototype")
#Component
public class WorkerThread implements Runnable {
#Autowired
private TaskBeanFactory taskBeanFactory;
#Autowired
private DataService dataService;
#Override
public void run() {
//iterate a Map of taskIds from the dataService
taskBeanFactory.setTaskName(TaskNameEnum.valueOf(taskEntry.getKey()));
GenericTask genericTask = taskBeanFactory.getObject();
//expecting genericTask to be of Type FileTask if called with one Key
//or of Type DataTask if called with another
}
}
}

Spring boot Autowiring service implementation in a bean fails

I'm trying to autowire a service implementation in one of my beans, but I keep getting a NoSuchBeanDefinitionException. This is my code:
Repository:
#Repository
public interface GlobalPropertiesRepository extends BaseRepository<GlobalProperties, Long>{
}
Service:
public interface GlobalPropertiesService {
GlobalProperties findOne(Long id);
}
Base Repository:
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.Repository;
import java.io.Serializable;
import java.util.List;
#NoRepositoryBean
public interface BaseRepository<T, ID extends Serializable> extends Repository<T, ID> {
void delete(T deleted);
List<T> findAll();
List<T> findAll(Iterable<ID> ids);
T findOne(ID id);
T save(T persisted);
<S extends T> S saveAndFlush(S entity);
}
Service Impl:
#Service("globalPropertiesService")
public class GlobalPropertiesServiceImpl implements GlobalPropertiesService{
#Autowired
GlobalPropertiesRepository globalPropertiesRepository;
#Override
public GlobalProperties findOne(Long id) {
return globalPropertiesRepository.findOne(id);
}
}
And then I autowire the implementation in one of my beans as below:
public class GlobalPropertiesLoader {
#Autowired
private GlobalPropertiesService globalPropertiesService;
private GlobalProperties globalProperties;
#PostConstruct
public void init(){
globalProperties = globalPropertiesService.findOne(1L);
}
public GlobalProperties getGlobalProperties(){
return globalProperties;
}
}
Finally, this is my Configuration class:
#Configuration
public class AppServiceConfig {
public AppServiceConfig() {
}
// Global properties
#Bean(name="globalPropertiesLoader")
public GlobalPropertiesLoader globalPropertiesLoader(){
return new GlobalPropertiesLoader();
}
}
This is my SpringBoot class:
#SpringBootApplication
#ComponentScan(basePackages="...")
public class TrackingService {
private static final Logger LOGGER = LoggerFactory.getLogger(TrackingService.class);
static AnnotationConfigApplicationContext context;
public static void main(String[] args) throws Exception {
SpringApplication.run(TrackingService.class, args);
ClassPathScanningCandidateComponentProvider provider =
new ClassPathScanningCandidateComponentProvider(true);
String basePackage = "...";
Set<BeanDefinition> components = provider.findCandidateComponents(basePackage);
for (BeanDefinition component : components) {
LOGGER.info("Component: "+component.getBeanClassName());
}
context = new AnnotationConfigApplicationContext();
context.refresh();
context.close();
}
}
Now, when I try to start the application, I get the following error in my GlobalPropertiesLoader bean:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [GlobalPropertiesService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}

Error while creating singleton in Java EE

I am new to Java EE an I am trying to add a new database table and program to an existing Java EE application that uses hibernate with persistence and spring framework. I am getting an error that says symbol not found
I've created 4 classes:-
public interface ncs_userInterface extends Persistable {
public abstract int getVersion();
public abstract String getPERSONIDNO();
public abstract String getFULLNAME();
public abstract long getID();
public abstract Date getCreationDate();
public abstract int getROLEID();
public abstract int getSCHEMEID();
public abstract String getSCHEMETITLE();
public abstract String getROLENAME();
public abstract void setVersion(int version);
public abstract void setPERSONIDNO(String PERSONIDNO);
public abstract void setFULLNAME(String FULLNAME);
public abstract void setID(long ID);
public abstract void setCreationdate(Date creationdate);
public abstract void setROLEID(int ROLEID);
public abstract void setSCHEMEID(int SCHEMEID);
public abstract void setSCHEMETITLE(String SCHEMETITLE);
public abstract void setROLENAME(String ROLENAME);
}
public class ncs_user extends PersistentObject implements ncs_userInterface{
private long ID;
private int version;
private Date creationdate;
private String PERSONIDNO;
private String FULLNAME;
private int ROLEID;
private String ROLENAME;
private int SCHEMEID;
private String SCHEMETITLE;
public ncs_user() {
}
public ncs_user(String PERSONIDNO, int version){
this.PERSONIDNO=PERSONIDNO;
this.version=version;
}
// All the getters and setters follow this but haven't listed them in this code
}
public abstract class ncs_userManager extends BasicManager{
protected static ncs_userManager INSTANCE;
public static final synchronized ncs_userManager getInstance() {
return INSTANCE;
}
public abstract void createAndPersistncs_user(ncs_userInterface newNcs_user);
public abstract List findNcs_usersByIdentity(String PERSONIDNO);
public abstract void updateNcs_user(ncs_userInterface changedNcs_user);
public abstract void deleteNcs_user(ncs_userInterface deletableNcs_user);
}
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Hibernate;
import org.hibernate.type.Type;
import org.olat.admin.user.delete.service.UserDeletionManager;
import org.olat.core.commons.persistence.DB;
import org.olat.core.commons.persistence.DBFactory;
import org.olat.core.gui.UserRequest;
import org.olat.core.gui.control.WindowControl;
import org.olat.core.id.Identity;
import org.olat.core.logging.OLog;
import org.olat.core.logging.Tracing;
import org.olat.core.util.coordinate.CoordinatorManager;
import org.olat.user.UserDataDeletable;
public class ncs_userManagerImpl extends ncs_userManager implements UserDataDeletable{
private static OLog log = Tracing.createLoggerFor(ncs_userManagerImpl.class);
public ncs_userManagerImpl(final UserDeletionManager userDeletionManager) {
userDeletionManager.registerDeletableUserData(this);
INSTANCE = this;
}
#Override
public void createAndPersistncs_user(final ncs_userInterface newNcs_user) {
final DB db = DBFactory.getInstance();
db.saveObject(newNcs_user);
if (log.isDebug()) {
log.debug("NCS_USER has been created: " + newNcs_user.getPERSONIDNO());
}
}
#Override
public List<ncs_userInterface> findNcs_usersByIdentity(final String PERSONIDNO) {
final String query = "from org.olat.ncs_user.ncs_user as b where b.PERSONIDNO = ?";
return DBFactory.getInstance().find(query, PERSONIDNO, Hibernate.LONG);
}
#Override
public void updateNcs_user(final ncs_userInterface changedNcs_user) {
DBFactory.getInstance().updateObject(changedNcs_user);
}
#Override
public void deleteNcs_user(final ncs_userInterface deletableNcs_user) {
DBFactory.getInstance().deleteObject(deletableNcs_user);
}
#Override
public void deleteUserData(final Identity identity, final String aString) {
}
}
I have also created a hibernate mapping file and a spring context file for the code above. I am trying to create a singleton using the following code:-
final ncs_userManager n;
n = new ncs_userManager.getInstance();
final ncs_userInterface newncs_user = new ncs_user(login, 0);
List l = n.findNcs_usersByIdentity(PERSONIDNO);
I am getting error in the line n = new ncs_userManager.getInstance():-
org/olat/admin/user/imp/ImportStep00.java:[205,75] error: cannot find symbol
I was wondering if someone could help me figure out what mistake I am making.
Remove the 'new' key word as its abstract class and you are calling static method of it.
Make it static and static final variable should be instantiated at the declaration time only.

Resources