Inject objects into Java

2

I'm used to working with Java EE where you can simply inject objects with the @Inject annotation however I do not know how to do it without using Java ee.

What I want is that the same object with the same instance can be used in different classes, for example for the following classes:

public class Main {

Foo foo;

public static void main(String[] args) {

    foo.setMensaje("hola");

    Bar bar = new Bar();
    bar.imprimirFoo();
}

}

Bar:

public class Bar {

private Foo foo;

public void imprimirFoo(){
    System.out.println(foo.getMensaje());
}

}

Foo:

public class Foo {
private String mensaje;

public String getMensaje() {
    return mensaje;
}

public void setMensaje(String mensaje) {
    this.mensaje = mensaje;
}

}

I would like you to print me twice hello, but I do not know how to do it without using the @Inject annotation

    
asked by gibran alexis moreno zuñiga 27.12.2017 в 23:10
source

2 answers

4

You must implement a design pattern called Singleton.

Remember that JEE is a set of services and in the services it provides there are already classes that implement a large number of design patterns.

If you still can not find the solution you need, implement it

see the following link

    
answered by 28.12.2017 / 01:04
source
1

First, I congratulate you for wanting to go beyond the use of products. If you continue like this you will soon be able to master any language and any framework easily.

The @inject signature is relative to the dependency injection pattern. I leave some links Spanish Wiki Description of the pattern creator (Martin Fowler) .

All this is part of the most modern techniques of object-oriented programming. The injection of dependencies is very similar in operation to the design pattern Strategy, well, and the initial set of design patterns You can find the book here is born everything we know today as Frameworks, Business Architectures, etc. You can see a friendlier description here in English and in different programming languages.

I hope it serves you.

    
answered by 04.01.2018 в 12:24