# Petite

**Petite** is one great little **IoC** container and components manager. *Petite* is easy to use since it requires no external configuration; it is incredibly fast, lightweight and super-small; so anyone can quickly grasp how it works. *Petite* is quite extensible and open for customization; and non-invasive.

### Quick Overview

The following bean shows some basic *Petite* usage:

```java
@PetiteBean
public class Foo {

    // dependency injected in the ctor
    @PetiteInject
    public Foo(ServiceOne one) {...}

    // dependency injected in a field
    @PetiteInject("serviceTwo")
    ServiceTwo two;

    // dependency injected with the method
    @PetiteInject
    public void injectService(ServiceThree three) {...}

    // dependency injected with the method
    public void injectService(
        @PetiteInject ServiceFour four) {...}

    // initialization method
    @PetiteInitMethod
    public void init() {...}

    public void foo() {
    }
}
```

`Foo` is *Petite* bean that defines several *injection points*, for different depending services from the container. Put this bean in the classpath and let `PetiteContainer` find it and register as a bean. Or register it manually if you like that way more.

### Why should I use it?

**Petite** is one of the lightest Java DI container around. Still, it supports sufficient most of features offered by other containers.

Here are the key features:

* property, method and constructor injection points.
* Instance life-cycle management, ordered initialization methods.
* Adding external objects to container.
* Wiring external objects with container's context.
* Creating objects by container.
* Automatic registration: no XML or code needed, just annotations.
* Programmatic configuration: using plain Java.
* Scopes: Prototype, Singleton and custom scopes.
* Thread local scope for thread singletons.
* HTTP session scope for session singletons.
* Designed to be extended.


# Container

*Petite* container manages registered beans: it takes care about lifecycle and **scope** of **registered** beans and resolves their dependences, i.e. **wires** them together. These are the three key aspects of *Petite*:

* Registration,
* Wiring, and
* Scope.

### Registration

Registration is all about how to register your beans and components into the *Petite* container.

`PetiteContainer` provides the single method for registering beans: `registerPetiteBean()` that takes following arguments:

* `type` - beans type, must be specified.
* `name` - beans name. If `null` the name will be resolved from the class.
* `scopeType` - bean scope. If `null` the scope will be resolved from the class.
* `wiringMode` - defines wiring mode. Also may be omitted.
* `define` - if set to `true`, injection points will be resolved.

This may be overwhelming, so just pay attention to first two arguments for now: the `type` and `name` (and provide `null`s to all others).

#### Developer-friendly registration

There is a developer-friendly alternative for beans registration. Instead of using `registerPetiteBean()` you may use `PetiteRegistry` class that offers nice, fluent interface for easier registration.

#### Registration using short type name

*Petite* beans may be named any way how you like it. However, there are two common scenarios, i.e. *naming convention* that frees you from writing bean names explicitly. The first scenario is to use uncapitalized short name of bean type, which is the default *Petite* naming convention:

```java
    PetiteContainer petite = new PetiteContainer();
    // bean "foo"
    petite.registerPetiteBean(Foo.class, null, null, null, false);
    // bean "bar"
    petite.registerPetiteBean(Bar.class, null, null, null, false);
```

or, using alternative way:

```java
    PetiteContainer petite = new PetiteContainer();
    PetiteRegistry registry = PetiteRegistry.of(petite);

    registry.bean(Foo.class).register();    // "foo"
    registry.bean(Bar.class).register();    // "bar"
```

Either way, our two beans are registered into the container. Beans are just simple POJOs:

```java
    public class Foo {
        Bar bar;
        public void foo() {
            bar.boo();
        }
    }

    public class Bar {
        public void boo() {}
    }
```

Registered beans can be lookuped by their names from container:

```java
    Foo foo = petite.getBean("foo");
```

Simple as that ;) Wait, don't call `foo.foo()` yet! By default `PetiteContaienr` needs annotations to resolve dependencies.

#### Registration using full type name

The second common scenario, i.e. a naming convention, is to use the full name of a bean type when the bean name is not provided.

```java
    PetiteContainer petite = new PetiteContainer();
    petite.config().setUseFullTypeNames(true);

    // register beans as before
```

The registration part stays the same - we just configured *Petite* to use full types names:

```java
    Foo foo = petite.getBean("org.jodd.Foo");
```

Good practice is not to mix naming convention when registering beans. Decide which one to use before development of your application starts. {: .attn}

### Initialization methods

*Petite* may invoke so-called **init methods** before bean instance is returned from the container. Init methods are no-argument methods marked with annotation `@PetiteInitMethod`. Example:

```java
    public class Bar {
        ...
        @PetiteInitMethod
        void init() {}
    }
```

By default, *Petite* will invoke init methods in unpredictable order (depends on JVM). Usually, it is the declaration order of methods in the class, but we can not guarantee that.

It is possible to specify the execution order of init methods, by setting `@PetiteInitMethod` element `order`. Order is a simple integer number. If order value is negative, those methods will be invoked last, starting from lesser number. For example, if methods are ordered as: `-1` and `-3`, the first will be invoked the method marked with order `-3`. Method marked with `-1` will be executed last. If order is not used, method will be invoked after the first ones (marked with positive order number) and the last ones (marked with negative order).

There are three different invocation strategies, that defines when init methods will be actually invoked:

* `POST_CONSTRUCT` - invoked just after a bean is created, before wiring and parameters injection.
* `POST_DEFINED` - invoked after bean has been wired with other beans, but before parameters injection
* `POST_INITALIZED` - invoked after bean has been completely initialized, after the [parameters injection](https://app.gitbook.com/s/-MUtuAZ822yX-ztrPX7U/parameters.html). This is the default strategy.

### Automatic registration

In all above examples, beans were registered into *Petite* container manually. But that is not the only way how we can do it. *Petite* offers automatic registration using `AutomagicPetiteConfigurator`: it will scan the classpath for all classes annotated with `@PetiteBean` annotation and automatically register them. Class scanning of `@PetiteBean` is quite fast: only the byte content is examined, so no other class is loaded during this process then the marked ones. It is possible to narrow the searched class path and fine-tune the scanning. Example:

```java
    @PetiteBean
    public class Foo {
    ...
    @PetiteBean
    public class Bar {
    ...
```

Petite automagic:

```java
    PetiteContainer petite = new PetiteContainer();
    new AutomagicPetiteConfigurator(petite).configure();
```

Now all *Petite*'s beans founded on the classpath will be registered in the container.

It is perfectly fine to combine automatic and manual configurations. `@PetiteBean` annotation is also considered during manual bean registration, so marked beans may be also manually registered just by class reference, other properties will be read from the annotation's elements.

### @PetiteBean

`@PetiteBean` is a simple *Petite* bean marker that contains just few elements:

* `value` - defines bean's name; by default bean name equals to

  uncapitalized bean class name.
* `scope` - bean's scope, by default it is `DefaultScope`.
* `wiring` - wiring mode (explained next).

Although `@PetiteBean` annotation is used for automatic registration, it will be also considered during manual registration!

### Accessing bean properties

It is possible to write and read property values of beans from the *Petite* context. This functionality is similar to `BeanUtil`, except it is applied on *Petite* context:

```java
    PetiteContainer pc = new PetiteContainer();
    pc.registerBean(PojoBean.class, "pojo", null, null, false);

    pc.setBeanProperty("pojo.foo1", "value");
    pc.getBeanProperty("pojo.foo2");

    pc.setBeanProperty("pojo.bean2.foo3", Integer.valueOf(173));
```

The only difference from `BeanUtil` is that first part of the property path (`pojo`) is actually the name of a registered bean.


# Wiring Components

When bean instance is created for the first time, *Petite* wires it with other registered beans. **Wiring** in *Petite* is the injection of required references into defined **injection points**.

### Wiring properties

By default, injection points in *Petite* components are marked with `@PetiteInject`. In our example, so far, container did not resolved the dependency since no annotation is used. To make previous example work, the `Foo` class needs to mark the injection point:

```java
    public class Foo {
        @PetiteInject
        Bar bar;

        public void foo() {
            bar.boo();
        }
    }
```

*Petite* now resolves dependency by injecting it in the annotated injection point. If annotation itself doesn't specify the bean name, it will be resolved from the injection point name (here thats field name).

Using setter methods for property injection point is not necessary, although they are used if defined. If a setter exist, *Petite* will inject required reference using a setter method, even if annotation is declared on a property field.

*Petite* knows how to handle circular dependencies during the wiring.

### Implicit bean references

If a bean reference name is not explicitly set by the annotation on an injection point, *Petite* will try to resolve the name. By default, bean name is resolved using the following values in given order:

1. property name,
2. uncapitalized short field type name,
3. long type name.

This order and values is fully configurable in *Petite* configuration. For example, it is possible to use only property names when resolving beans, or type's full name; or to change above order.

Knowing this, in the previous example *Petite* lookups for the following bean names:

1. `bar`
2. `bar` (ignored as equals to #1)
3. `org.jodd.Bar`

The first bean found will be injected into the marked injection point.

### Wiring methods

*Petite* also may use method injection points for wiring. Any method marked with `@PetiteInject` annotation is method injection point. References will be injected through any number of method arguments:

```java
    public class Foo {

        @PetiteInject
        void injectBar(Bar bar) {...}
        ...
    }
```

By default, reference names are resolved in the same way as for properties. Note that argument names are available using *Paramo* (another *Jodd* tool for resolving method argument names from bytecode), but only if classes are compiled in debug mode. To inject differently named references, they have to be specified in value element of `@PetiteInject` annotation, separated by a comma.

```java
    public class Foo {

        @PetiteInject("bar, one")
        void injectBoo(Bar bar, Zar zar) {...}
        ...
    }
```

You can ignore argument names (and not use *Paramo*) and rely only on argument types.

#### Using method arguments

There is a better way to markup the method - just by putting annotation on the arguments. Above example can be rewritten like this:

```java
    public class Foo {

        void injectBoo(
            @PetiteInject Bar bar,
            @PetiteInject("one") Zar zar) {...}
        ...
    }
```

The results is (almost) the same.

### Wiring constructors

*Petite* may wire beans and components using constructor. In the above example, `Foo` class may be modified as:

```java
    public class Foo {

        final Bar bar;

        @PetiteInject
        public Foo(Bar bar) {
            this.bar = bar;
        }

        public void foo() {
            bar.boo();
        }
    }
```

As for method injection points, constructor injection points are resolved in the same way as of methods and parameters. Annotating constructor arguments works too!

Constructor injection points have some limitations. There must be just one constructor injection point of a bean. If no constructor is annotated, *Petite* will take either the only available constructor, either the default one (when class has more then one constructor).

### Wiring modes

*Petite* supports several wiring modes of registered beans:

* `NONE` - no wiring, used in (rare) cases to prevent any possible

  wiring at all.
* `DEFAULT` - wiring mode is set by *Petite* container configuration.
* `STRICT` - strict wiring affects only property injection points. When

  strict mode is active, *Petite* only considers annotated fields (with

  `@PetiteInjection`) and throws an exception if required reference

  doesn't exist.
* `OPTIONAL` - relaxed version of previous mode also inject into

  annotated fields, but doesn't throw any exception for missing

  references.
* `AUTOWIRE` - tries to inject value in all bean fields. Missing

  references are ignored. Since all fields are examined, this mode is

  slightly slowest of all above. If field is annotated, injection

  information will be resolved from annotation, as usual.

Wiring mode of a bean may be defined independently from container.


# Scopes

Each *Petite* bean has its **scope**. Within the bean scope there is one and only one instance associated with the bean name. Scopes are defined during the registration and container then maintains instances within the scopes. When bean is lookuped by its name, *Petite* will return instance that is unique for bean's scope.

*Petite* supports several scopes. It is possible and easy to create new, custom ones.

Two most common and used scopes are: `ProtoScope` and `SingletonScope`. The `SingletonScope` is the default scope, used when no scope is specified explicitly. Beans of this scope are unique for the whole *Petite* container and will be instantiated by container only once. On the other hand, beans of `ProtoScope` are instantiated every time when lookuped.

Scope is defined during bean registration:

```java
PetiteContainer petite = new PetiteContainer();
petite.registerBean(Foo.class, null, ProtoScope.class, null, false);
petite.registerBean(Bar.class, null, null, null, false);
```

or, alternatively:

```java
registry.bean(Foo.class).scope(ProtoScope.class).register();
registry.bean(Bar.class).register();
```

Now, each time when `foo` is retrieved from the container, a new instance of `Foo` class will be created. And each time *Petite* will inject the same instance of `Boo` class, since scope of `boo` bean is (implicitly set as) `SingletonScope`.

### Available scopes

Here is the list of available *Petite* scopes:

* `ProtoScope` - beans are created each time requested.
* `SingletonScope` - beans are singletons for the container.
* `SessionScope` - beans are singletons in current HTTP session. To have this feature, the `RequestContextListener` must be used.
* `ThreadLocalScope` - beans are unique in the current thread.

### Using session scope

In order to use `SessionScope` (in a servlet container), the following listeners has to be added to the `web.xml`:

```markup
<?xml version="1.0" encoding="UTF-8"?>
<web-app ...>
    ...
    <listener>
        <listener-class>
            jodd.servlet.RequestContextListener
        </listener-class>
    </listener>
    ...
</web-app>
```

### Using session scope outside of container

When container has session scope beans, it can't be used out of servlet container. This makes testing outside of container hard. However, *Petite* has one nice feature: it is possible to register scopes manually. In regular use case, it is not necessary to deal with scopes registration, since scopes will be resolved and instantiated on their first usage. Anyhow, it is possible to register specific scope instance for any scope that will be used instead of required one.

For example, it is possible to replace session scope with the singleton scope, what is usually enough for the tests:

```java
PetiteContainer petite = new PetiteContainer();
petite.getManager().registerScope(SessionScope.class, new SingletonScope());
```

Now all session scope beans will be registered within singleton scope, assuming there is one and only one, big session.


# More Registration

Some more registration topics.

### Registering implementations

*Petite* register beans by their names. When working with simple POJOs, it is convenient to have bean names automatically generated from bean's class name. However, when there is an interface or abstract class to implement or extend with custom implementation, it is wise to name implementing bean with the interface name.

Here is some interface:

```java
    public interface Biz {
        void calculate();
    }
```

As said, implementation would be registered into *Petite* using interface name `biz`:

```java
    @PetiteBean("biz")
    public class DefaultBiz implements Biz {
        public void calculate() {}
    }
```

Now injection reference may be defined simply as:

```java
    public class BizUsage {

        @PetiteInject
        Biz biz;
        ...
    }
```

*Petite* will inject the implementation: `DefaultBiz`.

### Duplicated bean names

By default, when newly registered bean has the same bean name as one of already registered beans, the old bean registration will be simply discarded and the new one will be used. This might be important when providing custom implementations - the only important thing is the order of registration.

Nevertheless, *Petite* may be configured to detect duplicated bean names by setting this flag to `true`.

### Manual registration

*Petite* (i.e. `PetiteContainer`) offers methods for registering beans and for defining injection points and initial methods. Therefore, it is possibly to register and define everything in *Petite* using just Java, i.e. using manual registration.

*Petite* container configuration consist of:

* beans,
* scopes,
* init methods,
* injection points,
* provider definitions, and
* properties.

For each part of configuration, there is at least one method that registers it, like: `registerPetiteBean`, `registerPetitePropertyInjectionPoint`, `registerPetiteInitMethods`, etc.

When manually registering beans, there is one important thing to be aware of. There are two ways how a bean can be registered:

* **default** registration - on first lookup, registered beans will

  scanned for init methods, provider definitions and injection points

  (using annotations, if any found). This is, therefore, semi-manual

  registration in case if you have *Petite* annotations in your bean

  classes.
* **defined** - beans will be registered completely empty and all

  annotations (if exist) will be ignored.

#### PetiteRegistry

*Petite* provides helper class with only purpose to provide fluent registration: `PetiteRegistry`.

Here is how manual registration may look like:

```java
    PetiteContainer pc = new PetiteContainer();
    PetiteRegistry r = pc.createContainerRegistry();

    r.bean(SomeService.class).register();
    r.bean(PojoBean.class).name("pojo").register();

    r.wire("pojo").ctor().bind();
    r.wire("pojo").property("service").ref("someService").bind();
    r.wire("pojo").method("injectService").ref("someService").bind();
    r.init("pojo").invoke(POST_INITIALIZE).methods("init").register();
```

### Various ways of registration

Full, manual registration in plain Java may be unmaintainable and hard to follow. Because of *Petite* offers API for registration, there is unlimited number of ways how beans may be registered into the container. It is easy to build new system for beans registration, based on XML or on some other way, or to use different annotations and so on. Moreover, it is possible to influence the way how beans are registered and to utilize the whole process, as it will be shown next.

One real-life example is the following situation: some module consist of business components that are wired together using internal *Petite* container. User of this module is and should not be aware of *Petite*, but it still should be able to register custom versions of components and the new one as well. When registering new versions, the module prefers overriding of existing components instead of writing the completely new class, since logic behind components is a bit complex. In one word, for this module it is preferable to `extends` than to `implement`.

To hide *Petite* from module user, the following registration logic is being used. Module offers registration of the component types. Each time, module resolves the name of base class, i.e. the first class in the class hierarchy (not including `Object`, obviously). So base name is used when registering module component:

```java
    ...
    private String resolveBaseComponentName(Class component) {
        while(true) {
            Class superClass = component.getSuperclass();
            if (superClass.equals(Object.class)) {
                break;
            }
            component = superClass;
        }
        return PetiteUtil.resolveBeanName(component);
    }

    public final void registerComponent(Class component) {
        String name = resolveBaseComponentName(component);
        pc.removeBean(name);
        pc.registerBean(name, component);
    }
    ...
```

Custom version of existing component are registered with the names of their base classes. In case of this example, that was sufficient and yet simple solution. Later the above code was enhanced to skip abstract classes, but this is trivial thing to do and out of scope of this document.

More enhanced solution may be created from above example: one that performs more thoughtful checks of all super classes and/or interfaces, or to check what is the topmost annotated component and so on.

### Configure and register, then use

There is nothing that prevents from using *Petite* before all beans are registered. However, registering later some bean that replaces existing one might lead to unpredictable results. Although Petite will remove deprecated bean from internal structures as well from its scope, already injected instances of deprecated bean would stay alive.

It is strongly recommended to first configure *Petite* and to register all beans prior the usage.

### Adding objects

*Petite* allows any external object instance to be added as singleton bean into the container. Such instance is created outside of container and than assigned manually to it. As said, it becomes part of singleton scope, since *Petite* doesn't know how instance was created.

Usually, after adding, bean should be wired and its init method should be invoked:

```java
    PetiteContainer pc = new PetiteContainer();
    pc.registerBean(Foo.class, null, null, null, false);
    pc.registerBean(Zoo.class, null, null, null, false);
    Boo boo = new Boo();
    pc.addBean("boo", boo).wire(boo, true);
    ...
    Boo boo2 = (Boo) pc.getBean("boo");
```

In this example, `boo` and `boo2` points to the same instance. Furthermore, *Petite* performs injection into `boo` instance.

### Container self-registration

It is possible to registers *Petite* container instance into itself, simply by using `addSelf()` method.


# More Wiring

More wiring topics.

### Wiring external beans with container

All beans registered into the container will be wired. Wiring is lazy, i.e. it happens when some bean is requested (by bean name) for the first time in its scope. *Petite* then creates new bean instance and wires it.

All this happens for beans that are inside the container, i.e. registered. However, it is possible to wire any external object with the container context anytime during the runtime of the application.

```java
    PetiteContainer pc = ....
    Foo foo = new Foo();
    pc.wireBean(foo);
```

*Petite* will wire the `Foo` instance, but only using property and method injection (since bean is already created). Important is that `Foo` class is still not registered into the container. The only thing *Petite* stores is just some internal cache data, to speed up further injections for the same class.

It is possible to invoke init methods after wiring by setting second optional argument of `wireBean()` method to `true`.

### Creating beans with container

*Petite* allows something more: to create the bean by container. This makes constructor injection possible, what was not available for simple wiring.

```java
    PetiteContainer pc = ....
    Foo foo = pc.createBean(Foo.class);
```

Created beans are wired and init methods are invoked. However, created beans are **not** registered into the container.

### Mixing scopes

By default, *Petite* does not support *mixed scopes*. In other words, you should only inject beans of 'longer' scopes into beans of 'shorter' scopes. For example, you may inject singleton bean into session or prototype bean.

Doing opposite, by default, does not give any usable result. For example, if you inject session bean into the singleton target, only the one session bean will be wired! Singleton is created once, and therefore, it is wired once, and whatever session is available at that moment will be used for providing the session bean that will be injected into the target.

Fortunately, *Petite* provides scoped proxies that allows mixing scopes. Simply by enabling this flag, *Petite* will detect injections of mixed scopes and will inject a proxy instead. This scoped proxy lookup for the real bean and delegates method calls to it. By doing so, user will always access the correct bean.

Here is an example. First we need to enable mixed scopes:

```java
    PetiteContainer petiteContainer = ...
    petiteContainer.getConfig().setDetectMixedScopes(true);
    petiteContainer.getConfig().setWireScopedProxy(true);
```

We could use just the second flag; however, by enabling the detection there will be additional message in the log.

Here is the singleton bean:

```java
    @PetiteBean
    public class ItemService {

        @PetiteInject
        ItemManager itemManager;

        public ItemManager getItemManager() {
            return itemManager;
        }

        public void setItemManager(ItemManager itemManager) {
            this.itemManager = itemManager;
        }
    }
```

And here is the session scoped manager bean:

```java
    @PetiteBean(scope = SessionScope.class)
    public class ItemManager {
        ...
    }
```

If you lookup for the `ItemService`, you will always get the singleton instance. However, calling `getItemManager()` will return scoped proxy for `ItemManager`, that will delegate to the real bean instance stored in current session.

Note that scoped bean proxy is created only when mixed scopes are detected. In above example, if `ItemManager` is used injected into 'shorter' scoped bean, no scoped proxy is created.


# Beans Set Injection

There is one great (and new) feature of **Petite** container: it is possible to inject set of beans that are of the same type. All beans registered in the *Petite* container that implements some interface can be injected as a `Set` collection into a target bean.

### Example

Since this may sound a bit abstract at first sight, here is a simple example. Let's say we have an interface `SuperHero`:

```java
public interface SuperHero {
    String getHeroName();
}
```

Here are two `SuperHero` implementations marked as *Petite* beans:

```java
    @PetiteBean
    public class Batman implements SuperHero {
        public String getHeroName() {
            return "Batman";
        }
    }

    @PetiteBean
    public class Batgirl implements SuperHero {
        public String getHeroName() {
            return "Batgirl";
        }
    }
```

We can assume that there will be more `SuperHero` implementations, but at this moment we are not yet sure how many.

Now, we need to call all our superheros at one place, no matter how many implementations there are. All you have to do is specify the injection target as a `Set` field that has generics type of beans that has to be injected:

```java
    @PetiteBean
    public class GothamCity {

        @PetiteInject
        private Set<SuperHero> superHeros;

        public void callForHelp() {
            for (SuperHero superHero : superHeros) {
                System.out.println(superHero.getHeroName());
            }
        }
    }
```

After retrieving `GothamCity` from container, the field `superHeroes` will contain an `Set` instance. Set will contain all `Petite` beans that are of type `SuperHero`. Easy as that!

### Some features

* It works only for **fields**. Due to Java limitation (generic type

  erasure) it is possible to read generic type only of fields. So set

  injection will not work for methods and parameters.
* field names do not play any role in injection, just generic type.
* Set instance will be always created, even if there are no matching

  beans. This prevents null-checking.
* Only `Collection`, `Set` and `HashSet` can be used as field type.

  Although internal code practically allows all `Collection` types, we

  wanted to prevent possible vagueness of having other types (e.g.

  having a `List` with no defined beans order).

### For What It's Worth

We can think of interface methods as messages and target beans as message destinations (hey, who said *Event Bus* ? :) Let's see this idea in action.

Let's imagine that there is a requirement to send an notification e-mail every time when some user interaction occurs - e.g. when user confirms some payment. We don't have to be theoretical physicists to come with an interface like this one:

```java
    public interface PaymentEvent extends AppEvent {
        void paymentFinished(User user, Payment payment);
    }
```

Now we can code an implementation, `EmailPaymentEvent`. This one knows how to send an e-mail that contains all payment data to the user.

Let's now focus on usage in `PaymentService` - business class that actually performs the payment and that should call the event after successful payment.

#### Common approach

Usually, we could simply wire these beans, i.e. inject `EmailPaymentEvent` into the `PaymentService`\\:

```java
    @PetiteBean
    public class PaymentService {

        @PetiteInject
        EmailPaymentEvent emailPaymentEvent;

        public void processOrder(User user, Payment payment) {
            ...    // business code
            emailPaymentEvent.paymentFinished(user, payment);
        }
    }
```

And this would work. But...

#### Some problems

Sending emails can be a long process - especially if some reports has to be generated in PDF, etc.. Why stopping the user request thread for this? We could change the `PaymentEvent` code to support executors thread pool - but, to be hones, that is not the right place for that. Event doesn't have to be aware of the way how it is invoked.

Moreover, lets say that we need to send a SMS to the user, too, indicating successful payment. So we can code another class that sends an e-mail and wire it to the services. That would be too much error-prone work.

#### The new way

The solution is obvious - we can build a façade layer that will dispatch event call to all our implementations. However, we still have to manually wire all our implementations in the façade. So, the event delegation and dispatching logic would be hard-wired to the event implementations.

Instead, we can have the following code:

```java
    @PetiteBean
    public class PaymentEventDispatcher implements PaymentEvent {

        @PetiteInject
        Set<PaymentEvent> paymentEvents;

        void paymentFinished(User user, Payment payment){
            // process paymentEvents any way you need:
            // using thread pools, iterative etc.
        }
    }
```

So adding a new payment event is just about writing the implementation - and that's it! Everything will continue working as before.

Someone may noticed that `PaymentEventDispatcher` is also a `PaymentEvent` - since it is a dispatcher and façade, it make sense. But wait, since `PaymentEventDispatcher` is also part of the *Petite* context, wouldn\\'t it be also inside the injected set? Good thinking, but no - *Petite* is smart, so it will not put target injection instance in the set.

This gives us a new freedom - we can have independent dispatcher logics that would work for different events. For example, we can have a parallel executor, or iterative one, already implemented as an abstract dispatcher class that can be reused for your needs.

### New concept - your ideas?

This is a new concept in *Petite*. Although the explained functionality will stay, we feel there is more behind this idea that can enrich this concept.

Please feel free to contact us with your ideas about this interesting subject;)


# Petite Provider

*Petite* providers are methods that provide bean instances for injection into targets when needed. Providers are defined by their name, that can be used on injection points.

`@PetiteProvider` annotation may be used to annotate provider methods.

### Provider types

There are two provider types: *static* and *instance*.

**Static providers** are defined on static methods. For now, they can not be registered via annotations, but just with manual registration.

**Instance providers** are defined on instance methods of some *Petite* bean. Here you can use annotations to mark the method as a provider.

### Example

Lets define instance provider on this bean:

```java
    @PetiteBean
    public class Solar {

        @PetiteProvider("planet")
        public Planet planetProvider() {
            return new Planet();
        }
    }
```

This *Petite* bean defines provider with name '`planet`'. Here the name has been specified manually. You may omit provider name in annotation value - the provider name will be equal to method name, with stripped suffix `Provider` (if exist).

Providers are used by specifying their name on injection point. For example:

```java
    @PetiteBean
    public class Sun {

        @PetiteInject
        Planet planet;

        @Override
        public String toString() {
            return "Sun{" + planet + '}';
        }
    }
```

Here we specify the injection point '`planet`'. Since there is no other *Petite* bean named the same, *Petite* will lookup for provider and use provider method to get instance that will be injected into the field.

Note that provider method is registered in *Petite* bean. Therefore, on the place of injection *Petite* will lookup first for the bean that defines provider method! This way, for example, you can make providers that are different for each HTTP session, just by specifying that scope in provider method class.


# Setup

*Petite* uses annotation based configuration to make setup and configuration simple as possible. It doesn't depend on any external (XML) files; by default all configuration is done automagically, from Java. Nevertheless, it is easy to configure and extend *Petite* to match any requirements.

### Bean Iteration

At any time, all registered beans may be iterated. This is useful when some additional modification has to be performed on bean classes, after being registered. Method `beansIterator` iterates all beans - actually, it iterates all bean definitions! This means that beans may not be even initialized yet (there was no first lookup yet).

### Configuration

*Petite* container is quite configurable. Configuration is available via method `config()`.

#### defaultScope

Default scope for beans registration, when explicit scope is not specified. Default value: `SingletonScope.class`.

#### defaultWiringMode

Defines default wiring mode. Can be one of the following:

* `WiringMode.NONE` - no wiring,
* `WiringMode.STRICT` - throws an exception if injection failes

  (default),
* `WiringMode.OPTIONAL` - ignores unsuccessful injections
* `WiringMode.AUTOWIRE` - tries to wire all fields

Mode can be changed during runtime, although this is not recommended.

#### detectDuplicatedBeanNames

Flag for detecting duplicated bean names during registration (`false` by default). If set to `true`, *Petite* will throw an exception if bean with the same name already exists in the container.

#### resolveReferenceParameters

Flag for resolving parameter references (`true` by default). *Petite* parameters can define a value that contains value of other parameter. For example: `defineParameter("name", "${name2}");` will define parameter **name** with value equals to value of other parameter, **name2**.

#### useFullTypeNames

Defines what will be the default bean name, when no explicit name is provided. If set to `false` (default), uncapitalized simple type name will be used as bean name (for example, `app.service.SomeService` will be named as `someService`).

If set to `true`, then full bean type name will be used as bean name.

#### lookupReferences

Defines reference lookup order. When looking up for a bean reference, *Petite* may look for it in different ways. By default, the lookup order is the following:

* `PetiteReference.NAME`
* `PetiteReference.TYPE_SHORT_NAME`
* `PetiteReference.TYPE_FULL_NAME`

User may change or modify this lookup order.

#### useParamo

When set to `true` (default), *Petite* will use *Paramo* to extract constructor and method argument names - this information is not provided by java reflection API and must be read from debug information in bytecode. If set to `false`, injection by name will not be available for constructor and method arguments.


# Parameters

It is possible to define container parameters that will be injected into its beans after the wiring and before the init method invocation. Parameter is defined with the `String` name and value of any type.

By default, parameters are injected before init method invocation. In some cases, some init methods has to be invoked before setting the parameters. That is done by setting the `firstOff` element of `@PetiteInitMethod`, to indicate that init method has to be invoked before parameters injection.

### Convention

Parameters are bind to the container using the convention: parameter name starts with the bean name. Example:

```java
PetiteContainer pc = new PetiteContainer();
pc.registerBean(Foo.class);                 // registered as "foo"
pc.defineParameter("foo.name", "FOONAME");
...
Foo foo = (Foo) pc.getBean("foo");
foo.getName();                              // "FOONAME"
```

### Parameter References

Sometimes, one parameter has to be injected in several different beans. In order to prevent repeating, it is possible to use parameter references. Parameter reference is a parameter name surrounded with `${}` that points to some other parameter. It can occur anywhere in the value string. Nested references are supported as well. Example:

```java
    PetiteContainer pc = new PetiteContainer();
    pc.registerBean(Foo.class);                     // registered as "foo"
    pc.defineParameter("foo.name", "${name}");      // ref -> name
    pc.defineParameter("name", "${name${num}}");    // ref -> name2
    pc.defineParameter("num", "2");
    pc.defineParameter("name2", "FOONAME");

    ...
    Foo foo = (Foo) pc.getBean("foo");
    foo.getName();                                  // "FOONAME"
```

Resolving references is optional and, by default, is turned on.

*Petite* container doesn't detect circular dependencies when resolving parameters. {: .attn}

References can be escaped with single `\` character, while `\\` removes escaping effect and are resolved to single backslash.

References are resolved late, on their first injection.

### Loading from Map

It is possible to load parameters from any `Map` implementation, such as `Properties`.

```java
    Properties myProperties = ....;
    pc.defineParameters(myProperties);
```

### Loading from Props

It is possible to load parameters from **Props**, too:

```java
    Props myProps = ....;
    pc.defineParameters(myProps);
```


# FAQ

Everything you always wanted to know about *Petite* (but was afraid to ask).

### Do I really have to use annotations?

Of course NOT! By default *Petite* relies on annotations, but you are not forced to use them. There are two annotation-free alternatives:

* *automatic registration*, where all fields and methods and arguments are potential injection points. If there is a bean with matching reference name it will be injected as a dependency.
* *manual registration*, where you do all the wiring by yourself. You even have a fluent interface for that :) Power-to-the-people!


