Reputation: 2220
I really dont know why my CRUDRepository interface can't be injected.
I have a small app on Spring Boot and use CrudRepository:
public interface ActionLogRepository extends CrudRepository<ActionLog, Integer> {
}
In my service class I have a method:
@Service
public class ActionRecordServiceImpl implements ActionRecordService {
@Override
@Transactional
public void deleteActionRecord(Date date, String domain) {
Set<Action> actions= myActions...(the code delibrately shortened)
for (Action a : actions) {
actionRepository.delete(a);
}
}
}
}
Next I have my Interceptor - I want to catch all delete operations and save these logs in database:
public class ActionTrackerInterceptor extends EmptyInterceptor {
// called when record is deleted.
public void onDelete(Object entity, Serializable id, Object[] state,
String[] propertyNames, Type[] types) {
Action act = (Action) entity;
String action = "DELETED";
ActionLog actionLog = new ActionLog(...some data inserted...);
MyActionLogUtil util = new MyActionLogUtil();
util.logIt("DELETED", actionLog);
actionLogRepository.save(actionLog);
System.out.println("Record " + entity + " is deleted.");
}
And my method util.LogIt looks like:
@Component
public class MyActionLogUtilImpl implements ActionyLogUtil {
private ActionLogRepository actionLogRepository;
@Autowired
public void setActionLogRepository(ActionLogRepository actionLogRepository) {
this.actionLogRepository = actionLogRepository;
}
@Override
public void logIt(String action, ActionLog entity) {
try {
ActionLog actionLog = null; // = new ActionLog(...some data inserted...)
actionLogRepository.save(actionLog);
} finally {
}
}
}
When my app is starting, the method setActionLogRepository in MyActionLogUtilImpl is set and ActionLogRepository is correctly injected (not null value). But when debugging, in the method MyActionLogUtilImpl.LogIt IS MY actionLogRepository NULL!
My main class with @SpringBootApplication is at the top of the packages so the ComponentScan issue is not the point here.
The question is WHY? Another transaction? I really don't know what's the problem. I've read all similar topics in INternet... Please help me. Thank you.
Regards Matley
Upvotes: 0
Views: 197
Reputation: 3416
In your ActionTrackerInterceptor
:
MyActionLogUtil util = new MyActionLogUtil();
You are creating a new instance of your "Util" class manually rather than using the one Spring created at application startup (which actually have a correct reference to your repository).
It's not about transaction management, it's about core DI functionality. Make sure you read the Spring docs for further info how DI works in general.
Upvotes: 1