Что такое inject java

Использование стандартных аннотаций JSR 330

Начиная со Spring 3.0, Spring предлагает поддержку аннотаций из JSR-330 (Внедрение зависимостей). Эти аннотации сканируются так же, как и аннотации Spring. Чтобы использовать их, вам необходимо иметь соответствующие jar-файлы в вашем пути классов.

Если вы используете Maven, артефакт javax.inject находится в стандартном репозитории Maven ( https://repo1.maven.org/maven2/javax/inject/javax.inject/1/). Вы можете добавить следующую зависимость в свой файл pom.xml:

 javax.inject javax.inject 1 

Внедрение зависимостей с помощью @Inject и @Named

Вместо @Autowired вы можете использовать @javax.inject.Inject следующим образом:

import javax.inject.Inject; public class SimpleMovieLister < private MovieFinder movieFinder; @Inject public void setMovieFinder(MovieFinder movieFinder) < this.movieFinder = movieFinder; >public void listMovies() < this.movieFinder.findMovies(. ); // . >>
import javax.inject.Inject class SimpleMovieLister < @Inject lateinit var movieFinder: MovieFinder fun listMovies() < movieFinder.findMovies(. ) // . >>

Как и в случае с @Autowired , вы можете использовать @Inject на уровне поля, метода и аргумента конструктора. Более того, вы можете объявить свою точку внедрения как Provider , что позволит получить доступ по требованию к бинам с более узкой областью видимости или отложенный доступ к другим бинам через вызов Provider.get() . В следующем примере предложен вариант предыдущего примера:

import javax.inject.Inject; import javax.inject.Provider; public class SimpleMovieLister < private ProvidermovieFinder; @Inject public void setMovieFinder(Provider movieFinder) < this.movieFinder = movieFinder; >public void listMovies() < this.movieFinder.get().findMovies(. ); // . >>
import javax.inject.Inject class SimpleMovieLister < @Inject lateinit var movieFinder: Providerfun listMovies() < movieFinder.get().findMovies(. ) // . >>

Если необходимо использовать полное имя для зависимости, которую нужно внедрить, вам потребуется использовать аннотацию @Named , как показано в следующем примере:

import javax.inject.Inject; import javax.inject.Named; public class SimpleMovieLister < private MovieFinder movieFinder; @Inject public void setMovieFinder(@Named("main") MovieFinder movieFinder) < this.movieFinder = movieFinder; >// . >
import javax.inject.Inject import javax.inject.Named class SimpleMovieLister < private lateinit var movieFinder: MovieFinder @Inject fun setMovieFinder(@Named("main") movieFinder: MovieFinder) < this.movieFinder = movieFinder >// . >

Как и @Autowired , @Inject также можно использовать с java.util.Optional или @Nullable . Это тем более применимо в данном случае, поскольку @Inject не имеет required атрибута. Следующая пара примеров показывает, как использовать @Inject и @Nullable :

public class SimpleMovieLister < @Inject public void setMovieFinder(OptionalmovieFinder) < // . >>
public class SimpleMovieLister < @Inject public void setMovieFinder(@Nullable MovieFinder movieFinder) < // . >>

@Named и @ManagedBean : Стандартные эквиваленты аннотации @Component

Вместо @Component можно использовать @javax.inject.Named или javax.annotation.ManagedBean , как показано в следующем примере:

import javax.inject.Inject; import javax.inject.Named; @Named("movieListener") // можно также использовать @ManagedBean("movieListener") public class SimpleMovieLister < private MovieFinder movieFinder; @Inject public void setMovieFinder(MovieFinder movieFinder) < this.movieFinder = movieFinder; >// . >
import javax.inject.Inject import javax.inject.Named @Named("movieListener") // можно также использовать @ManagedBean("movieListener") class SimpleMovieLister < @Inject lateinit var movieFinder: MovieFinder // . >

Очень часто используется @Component без указания имени компонента. Аналогичным образом можно использовать @Named , как показано в следующем примере:

import javax.inject.Inject; import javax.inject.Named; @Named public class SimpleMovieLister < private MovieFinder movieFinder; @Inject public void setMovieFinder(MovieFinder movieFinder) < this.movieFinder = movieFinder; >// . >
import javax.inject.Inject import javax.inject.Named @Named class SimpleMovieLister < @Inject lateinit var movieFinder: MovieFinder // . >

Если вы задействуете @Named или @ManagedBean , то использовать сканирование компонентов можно точно так же, как и при использовании аннотаций Spring, как показано в следующем примере:

@Configuration @ComponentScan(basePackages = "org.example") public class AppConfig < // . >
@Configuration @ComponentScan(basePackages = ["org.example"]) class AppConfig < // . >

В отличие от @Component , аннотации @Named из JSR-330 и @ManagedBean из JSR-250 не являются составными. Для создания специальных аннотаций компонентов следует использовать модель стереотипов Spring.

Читайте также:  Java arraylist from iterator

Ограничения стандартных аннотаций JSR-330

При работе со стандартными аннотациями следует знать, что некоторые важные функции будут недоступны, как показано в следующей таблице:

У @Inject нет атрибута «required». Вместо этогоможно использовать Optional из Java 8

JSR-330 не предоставляет составную модель, только способ идентификации именованных компонентов.

Область доступности по умолчанию из JSR-330 похожа на область доступности на уровне prototype из Spring. Однако для того, чтобы соответствовать общим настройкам Spring, бин из JSR-330, объявленный в контейнере Spring, по умолчанию является singleton . Чтобы использовать область доступности , отличную от singleton , необходимо использовать аннотацию @Scope из Spring. javax.inject также предоставляет возможность использовать аннотацию @Scope. Тем не менее, она предназначена только для создания собственных аннотаций.

javax.inject.Qualifier – это просто мета-аннотация для создания кастомных квалификаторов. Конкретные String квалификаторы (наподобие @Qualifier из Spring с некоторым значением) могут быть связаны через javax.inject.Named .

Источник

Что такое inject java

Identifies injectable constructors, methods, and fields. May apply to static as well as instance members. An injectable member may have any access modifier (private, package-private, protected, public). Constructors are injected first, followed by fields, and then methods. Fields and methods in superclasses are injected before those in subclasses. Ordering of injection among fields and among methods in the same class is not specified. Injectable constructors are annotated with @Inject and accept zero or more dependencies as arguments. @Inject can apply to at most one constructor per class.

@Inject ConstructorModifiersopt SimpleTypeName(FormalParameterListopt) Throwsopt ConstructorBody

@Inject is optional for public, no-argument constructors when no other constructors are present. This enables injectors to invoke default constructors.

@Injectopt Annotationsopt public SimpleTypeName() Throwsopt ConstructorBody

  • are annotated with @Inject .
  • are not abstract.
  • do not declare type parameters of their own.
  • may return a result
  • may have any otherwise valid name.
  • accept zero or more dependencies as arguments.

@Inject MethodModifiersopt ResultType Identifier(FormalParameterListopt) Throwsopt MethodBody

The injector ignores the result of an injected method, but non- void return types are allowed to support use of the method in other contexts (builder-style method chaining, for example).

public class Car < // Injectable constructor @Inject public Car(Engine engine) < . >// Injectable field @Inject private Provider seatProvider; // Injectable package-private method @Inject void install(Windshield windshield, Trunk trunk) < . >>

A method annotated with @Inject that overrides another method annotated with @Inject will only be injected once per injection request per instance. A method with no @Inject annotation that overrides a method annotated with @Inject will not be injected.

Injection of members annotated with @Inject is required. While an injectable member may use any accessibility modifier (including private), platform or injector limitations (like security restrictions or lack of reflection support) might preclude injection of non-public members.

Читайте также:  Поставить в начало массива php

Qualifiers

A qualifier may annotate an injectable field or parameter and, combined with the type, identify the implementation to inject. Qualifiers are optional, and when used with @Inject in injector-independent classes, no more than one qualifier should annotate a single field or parameter. The qualifiers are bold in the following example:

public class Car < @Inject private @Leather Provider seatProvider; @Inject void install(@Tinted Windshield windshield, @Big Trunk trunk) < . >>

If one injectable method overrides another, the overriding method's parameters do not automatically inherit qualifiers from the overridden method's parameters.

Injectable Values

For example, the user might use external configuration to pick an implementation of T. Beyond that, which values are injected depend upon the injector implementation and its configuration.

Circular Dependencies

Detecting and resolving circular dependencies is left as an exercise for the injector implementation. Circular dependencies between two constructors is an obvious problem, but you can also have a circular dependency between injectable fields or methods:

When constructing an instance of A , a naive injector implementation might go into an infinite loop constructing an instance of B to set on A , a second instance of A to set on B , a second instance of B to set on the second instance of A , and so on.

A conservative injector might detect the circular dependency at build time and generate an error, at which point the programmer could break the circular dependency by injecting Provider or Provider instead of A or B respectively. Calling get() on the provider directly from the constructor or method it was injected into defeats the provider's ability to break up circular dependencies. In the case of method or field injection, scoping one of the dependencies (using singleton scope, for example) may also enable a valid circular relationship.

  • Summary:
  • Field |
  • Required |
  • Optional
  • Detail:
  • Field |
  • Element

Copyright © 1996-2017, Oracle and/or its affiliates. All Rights Reserved. Use is subject to license terms.

Источник

Что такое inject java

Identifies injectable constructors, methods, and fields. May apply to static as well as instance members. An injectable member may have any access modifier (private, package-private, protected, public). Constructors are injected first, followed by fields, and then methods. Fields and methods in superclasses are injected before those in subclasses. Ordering of injection among fields and among methods in the same class is not specified. Injectable constructors are annotated with @Inject and accept zero or more dependencies as arguments. @Inject can apply to at most one constructor per class.

@Inject ConstructorModifiersopt SimpleTypeName(FormalParameterListopt) Throwsopt ConstructorBody

@Inject is optional for public, no-argument constructors when no other constructors are present. This enables injectors to invoke default constructors.

@Injectopt Annotationsopt public SimpleTypeName() Throwsopt ConstructorBody

  • are annotated with @Inject .
  • are not abstract.
  • do not declare type parameters of their own.
  • may return a result
  • may have any otherwise valid name.
  • accept zero or more dependencies as arguments.

@Inject MethodModifiersopt ResultType Identifier(FormalParameterListopt) Throwsopt MethodBody

The injector ignores the result of an injected method, but non- void return types are allowed to support use of the method in other contexts (builder-style method chaining, for example).

public class Car < // Injectable constructor @Inject public Car(Engine engine) < . >// Injectable field @Inject private Provider seatProvider; // Injectable package-private method @Inject void install(Windshield windshield, Trunk trunk) < . >>

A method annotated with @Inject that overrides another method annotated with @Inject will only be injected once per injection request per instance. A method with no @Inject annotation that overrides a method annotated with @Inject will not be injected.

Читайте также:  Java runtime environment jre версии 11

Injection of members annotated with @Inject is required. While an injectable member may use any accessibility modifier (including private), platform or injector limitations (like security restrictions or lack of reflection support) might preclude injection of non-public members.

Qualifiers

A qualifier may annotate an injectable field or parameter and, combined with the type, identify the implementation to inject. Qualifiers are optional, and when used with @Inject in injector-independent classes, no more than one qualifier should annotate a single field or parameter. The qualifiers are bold in the following example:

public class Car < @Inject private @Leather Provider seatProvider; @Inject void install(@Tinted Windshield windshield, @Big Trunk trunk) < . >>

If one injectable method overrides another, the overriding method's parameters do not automatically inherit qualifiers from the overridden method's parameters.

Injectable Values

For example, the user might use external configuration to pick an implementation of T. Beyond that, which values are injected depend upon the injector implementation and its configuration.

Circular Dependencies

Detecting and resolving circular dependencies is left as an exercise for the injector implementation. Circular dependencies between two constructors is an obvious problem, but you can also have a circular dependency between injectable fields or methods:

When constructing an instance of A , a naive injector implementation might go into an infinite loop constructing an instance of B to set on A , a second instance of A to set on B , a second instance of B to set on the second instance of A , and so on.

A conservative injector might detect the circular dependency at build time and generate an error, at which point the programmer could break the circular dependency by injecting Provider or Provider instead of A or B respectively. Calling get() on the provider directly from the constructor or method it was injected into defeats the provider's ability to break up circular dependencies. In the case of method or field injection, scoping one of the dependencies (using singleton scope, for example) may also enable a valid circular relationship.

  • Summary:
  • Field |
  • Required |
  • Optional
  • Detail:
  • Field |
  • Element

Copyright © 1996-2015, Oracle and/or its affiliates. All Rights Reserved. Use is subject to license terms.

Источник

Оцените статью