0

I need to achieve dependency injection using PicoContainer without passing constructor parameters, current setup:

public class Shared_Data  {

    public Account_Pojo account_pojo;

    public Shared_Data(Account_Pojo account_pojo) {
        this.account_pojo = account_pojo;
    }

In the above example I need to achieve DI using PicoContainer without passing: Account_Pojo account_pojo as a parameter to the constructor, is this even possible?

I have tried the following with no luck:

public class Shared_Data {
    public Account_Pojo account_pojo;

    public Shared_Data() {
    }

    public void setAccount_pojo(Account_Pojo account_pojo) {
        this.account_pojo = account_pojo;
    }

    public Account_Pojo getAccount_pojo() {
        setAccount_pojo(account_pojo);
        return account_pojo;
    }
}
Gbru
  • 1,065
  • 3
  • 24
  • 56

1 Answers1

2

You can set up a pico container with a SetterInjection component factory[0].

pico = new DefaultPicoContainer(new SetterInjection());
pico.addComponent(Account_Pojo.class);

Something like this should work.

[0] http://picocontainer.com/setter-injection.html

Elias
  • 1,532
  • 8
  • 19
  • tried the following with no luck :/ DefaultPicoContainer pico = new DefaultPicoContainer(new SetterInjection()); pico.addComponent(Account_Pojo.class); Account_Pojo account_pojo = pico.getComponent(Account_Pojo.class); account_pojo.setFirstName("test123"); – Gbru Oct 02 '19 at 11:45
  • What is no luck exactly? Compile errors, stack traces? – Elias Oct 02 '19 at 11:46
  • Seems Im seeing the following exception: org.picocontainer.injectors.AbstractInjector$UnsatisfiableDependenciesException: sharedStepsUtils.account.Account_Pojo has unsatisfied dependencies [class java.lang.String] for members [public void sharedStepsUtils.account.Account_Pojo.setEmailAddress(java.lang.String).. – Gbru Oct 02 '19 at 11:53
  • 1
    @Gbru Side-effect of using `SetterInjection` component factory is that all methods starting with `set` will be used to create the component. `SetterInjection` accepts a constructor argument to change this prefix, so you can call your component-configuration methods (for example) `initAccount_pojo` and leave your other setters as-is: `new DefaultPicoContainer(new SetterInjection("init"));` – Elias Oct 02 '19 at 12:05
  • thanks @Elias looks like the following works, when added to a sole cucumber step just need to figure out why it doesnt work when calling the get method from a different step: DefaultPicoContainer pico = new DefaultPicoContainer(new SetterInjection("init")); pico.addComponent(Account_Pojo.class); Account_Pojo account_pojo = pico.getComponent(Account_Pojo.class); account_pojo.setFirstName("joe"); account_pojo.getFirstName(); – Gbru Oct 02 '19 at 12:31
  • @Gbru You did not provide details of your `getFirstName` method. Consider accepting the answer and asking a new one with your new question. – Elias Oct 02 '19 at 12:38