-2

I have a model for service to use. But the autowired annotation returns null value. However this autowire works well in service. Is there any to do in the Module class?

public class Module{
    private int id;
    private String name;
    private ArrayList<Function> functions;

    @Autowired
    private SysModuleLgDao sysModuleLgDao;



    public Module() {
        sysModuleLgDao.doSth();
    }
}

This is my repo class:

@Repository
public interface SysModuleLgDao extends JpaRepository<SysModuleLgEntity, Long> {
    public List<SysModuleLgEntity> findByModuleLgIdAndLanguageId(long moduleLgId,long languageId);
}
kryger
  • 12,906
  • 8
  • 44
  • 65
travistam
  • 43
  • 8

1 Answers1

0

Object's constructor is called before Spring has a chance to do the wiring, so sysModuleLgDao reference is in its default state (i.e. null). Spring's context loading happens in a later phase, long after the default constructor has been called.

You can work around the problem by performing doSth in a different lifecycle phase, after the Spring bean has been constructed. This can be achieved via the @PostContstruct annotation:

public class Module {
    @Autowired
    private SysModuleLgDao sysModuleLgDao;

    @PostConstruct
    public void initialise() {
        // at this point sysModuleLgDao is already wired by Spring
        sysModuleLgDao.doSth();
    }
}

More details here: Why use @PostConstruct?

Community
  • 1
  • 1
kryger
  • 12,906
  • 8
  • 44
  • 65
  • The PostConstruct method seems not to be called in the object new. Is there any config in spring boot? – travistam Dec 30 '15 at 07:52
  • Yes, you need configuration and yours is apparently incorrect but you didn't show any so there's no way to tell what's wrong. Also, what's "object new"? – kryger Dec 30 '15 at 08:48
  • I would like to call constructor directly from my service like `@Service("MyService")` `public class MyService(` `public void myMethod(){` `Module module = new Module();` `}` `)` – travistam Dec 30 '15 at 08:55
  • In this case, your question is a duplicate of http://stackoverflow.com/q/19896870/1240557 (explanations in the accepted answer) – kryger Dec 30 '15 at 11:23