In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article focuses on "how Sprin controls inversion and dependency injection". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how Sprin controls inversion and dependency injection.
Control the type of inversion
Inversion of Control (IOC) is designed to provide a simpler mechanism for setting component dependencies and managing them throughout the life cycle. In general, control inversion can be divided into two subtypes: dependency injection (DI) and dependency lookup (DL), each of which can be further decomposed into concrete implementations of IOC services.
1. Dependency Lookup 1.1 dependency pull
Dependency pull (Dependency Pull), that is, extracting dependencies from the registry as needed, the following code shows Spring-based dependency pull
Public class DependencyPull {public static void main (String [] args) {ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext ("spring/app-context.xml"); ctx.getBean ("renderer", MessageRenderer.class);} 1.2 context dependent lookup
Context-dependent lookup (contextualized dependency lookup,CDL), which is also a subtype of dependency lookup, is somewhat similar to dependency pull, but in CDL, lookup is performed against a container that manages resources, which is usually provided by an application server or framework (Tomcat, JBoss, Spring). For example, the following code shows a container interface that provides a dependent lookup service
Public interface Container {/ / get the corresponding dependency Object getDependency (String key) according to key;}
CDL works by having the component implement the following code interface
Public interface ManagedComponent {void performLookup (Container container);}
The component needs to implement this interface. When the container is ready to pass the dependency to the component, it will call the performLookup () method of each component in turn, and then the component can use the Container interface to find the desired dependency.
Public class ContextualizedDependencyLookup implements ManagedComponent {private Dependency dependency; @ Override public void performLookup (Container container) {this.dependency = (Dependency) container.getDependency ("myDependency");} @ Override public String toString () {return dependency.toString ();}} 2. Dependency injection 2.1 Constructor injection
Constructor dependency injection occurs when dependencies are provided in the constructor of a component
Public class ConstructorInjection {private Dependency dependency; public ConstructorInjection (Dependency dependency) {this.dependency = dependency;} @ Override public String toString () {return dependency.toString ();}} 2.2 setter function injection
The Ioc container injects dependencies of components through JavaBean-style setter methods
Public class SetterInjection {private Dependency dependency; public void setDependency (Dependency dependency) {this.dependency = dependency;} @ Override public String toString () {return dependency.toString ();}
In Spring, another type of injection called field injection (field injection) is also supported, which will be introduced later when you learn to auto-assemble with the @ Autowire annotation
Control reversal in Spring 1. Bean and BeanFactory
At the core of Spring's dependency injection container is BeanFactory, which manages components, including dependencies and their lifecycles. If we want to get a component (Bean), we must create an instance that implements the BeanFactory interface and configure it
Although BeanFactory can be configured programmatically, it is more common to configure it externally using some kind of configuration file. The Bean configuration can be represented by an instance of a class that implements the BeanDefinition interface. For any BeanFactory implementation class that implements the BeanDefinitionReader interface, you can use PropertiesBeanDefinitionReader or XmlBeanDefinitionReader to read BeanDefinition data from the configuration file
Define a set of interfaces:
Public interface Oracle {String output ();} public class OracleImpl implements Oracle {@ Override public String output () {return "hello world";}}
Next, let's take a look at how Spring's BeanFactory is initialized and used to get a Bean instance.
Public class XmlConfigWithBeanFactory {public static void main (String [] args) {/ / DefaultListableBeanFactory is one of the two main BeanFactory implementations provided by Spring DefaultListableBeanFactory factory = new DefaultListableBeanFactory (); XmlBeanDefinitionReader rdr = new XmlBeanDefinitionReader (factory); / / use XmlBeanDefinitionReader to read BeanDefinition information rdr.loadBeanDefinitions (new ClassPathResource ("spring/xml-bean-factory-config.xml")) from XML files / / use the name oracle configured in the XML configuration file to get bean Oracle oracle = (Oracle) factory.getBean ("oracle"); System.out.println (oracle.getInfo ());}}
The ApplicationContext interface is an extension of BeanFactory, providing other services such as transactions and AOP in addition to DI services. When developing Spring-based applications, it is recommended to interact with Spring through the ApplicationContext interface
two。 Set up Spring configuration 2.1 XML configuration
For XML configuration, you need to declare the basic namespace information provided by Spring that the application needs. The configuration shown below declares only the namespace used to define the bean.
2.2 Annotation configuration
To use Spring's annotation support in your application, you need to declare in the XML configuration
The tag tells Spring to scan the code to find the bean injected by annotations such as @ Component, and the bean that supports annotations such as @ Autowire under the specified package (and all its subpackages)
2.3 Java configuration
The configuration class uses @ Configuration annotations and contains methods annotated with @ Bean that are called directly by the IOC container to instantiate bean,bean with the same name as the method used to create it.
@ Configurationpublic class HelloWorldConfiguration {@ Bean public MessageProvider provider () {return new HelloWorldMessageProvider ();} @ Bean public MessageRender render () {StandardOutMessageRender render = new StandardOutMessageRender (); render.setMessageProvider (provider ()); return render;}}
If you want to read configuration information from this class, you need a different ApplicationContext implementation
Public class HelloWorldSpringAnnotated {public static void main (String [] args) {AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext (HelloWorldConfiguration.class); MessageRender render = ctx.getBean ("render", MessageRender.class); render.render ();}} 3. Setter injection
To configure setter injection using XML configuration, you need to specify a tag under the tag to inject a dependency into it
If you use annotations, you only need to add a @ Autowired annotation to the setter method
@ Service ("render") public class StandardOutMessageRender implements MessageRender {... @ Override @ Autowired public void setMessageProvider (MessageProvider messageProvider) {this.messageProvider = messageProvider;} 4. The constructor injects public class ConfigurableMessageProvider implements MessageProvider {private String message; public ConfigurableMessageProvider (String message) {this.message = message;} @ Override public String getMessage () {return null;}}
Using XML injection
Use annotations
@ Servicepublic class ConfigurableMessageProvider implements MessageProvider {private String message; @ Autowired public ConfigurableMessageProvider (@ Value ("hello world") String message) {this.message = message;} @ Override public String getMessage () {return null;}} so far, I believe you have a better understanding of "how Sprin controls inversion and dependency injection". Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.