Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to stuff Bean into a Spring container

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the knowledge of "how to stuff Bean into a Spring container". In the operation of practical cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Agent Bean registers with the Spring container

Bean Registration the technical scenario of Bean registration, MyBatis is the most common of the technical frameworks we use every day. By defining an interface when using MyBatis, you do not need to write an implementation class, but this interface can be associated with the configured SQL statement, and the corresponding results can be returned when performing the corresponding database operation. Then the Bean proxy and registration are used for the operation of this interface and database. We all know that class calls cannot directly call interfaces that are not implemented, so we need to generate corresponding implementation classes for the interfaces by proxy. Next, put the proxy class into the FactoryBean implementation of Spring, and finally register the FactoryBean implementation class with the Spring container. Now that your proxy class is registered with the Spring container, you can annotate it into the property.

Following this implementation, let's take a look at how a Bean registration process is implemented in the code.

1. Define interface public interface IUserDao {

String queryUserInfo ()

}

First define an interface similar to DAO, which is very common when using MyBatis. We will proxy and register this interface later. two。 Class proxy implements ClassLoader classLoader = Thread.currentThread (). GetContextClassLoader ()

Class [] classes = {IUserDao.class}

InvocationHandler handler = (proxy, method, args)-> "you are represented" + method.getName ()

IUserDao userDao = (IUserDao) Proxy.newProxyInstance (classLoader, classes, handler)

String res = userDao.queryUserInfo ()

Logger.info ("Test results: {}", res)

The proxy method of Java itself is relatively simple to use, and the usage is very fixed. InvocationHandler is an interface class, and its corresponding implementation is the concrete implementation of the proxy object. Finally, the proxy is handed over to Proxy to create the proxy object, Proxy.newProxyInstance. 3. Implement Bean factory public class ProxyBeanFactory implements FactoryBean {

@ Override

Public Object getObject () throws Exception {

ClassLoader classLoader = Thread.currentThread () .getContextClassLoader ()

Class [] classes = {IUserDao.class}

InvocationHandler handler = (proxy, method, args)-> "you are represented" + method.getName ()

Return Proxy.newProxyInstance (classLoader, classes, handler)

}

@ Override

Public Class getObjectType () {

Return IUserDao.class

}

}

FactoryBean plays a second role in spring. It has nearly 70 younger brothers (implement its interface definition), so it has three methods. T getObject () throws Exception; returns the bean instance object Class getObjectType (); returns the instance class type boolean isSingleton (); determines whether the singleton is placed in the single instance cache pool in the Spring container. Here we put the above object using the Java proxy into the getObject () method, so now the object obtained from Spring is our proxy object. 4. Bean registers public class RegisterBeanFactory implements BeanDefinitionRegistryPostProcessor {

@ Override

Public void postProcessBeanDefinitionRegistry (BeanDefinitionRegistry registry) throws BeansException {

GenericBeanDefinition beanDefinition = new GenericBeanDefinition ()

BeanDefinition.setBeanClass (ProxyBeanFactory.class)

BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder (beanDefinition, "userDao")

BeanDefinitionReaderUtils.registerBeanDefinition (definitionHolder, registry)

}

}

In the Bean management of Spring, all Bean will eventually be registered with the class DefaultListableBeanFactory. The main contents of the above code include:

Implement the BeanDefinitionRegistryPostProcessor.postProcessBeanDefinitionRegistry method to get the Bean registration object. Define Bean,GenericBeanDefinition, which mainly sets up our proxy class factory. Create the Bean definition processing class, BeanDefinitionHolder, the main parameters required here; define Bean and the name setBeanClass (ProxyBeanFactory.class). Finally, register our own bean with the spring container, and registry.registerBeanDefinition () test to verify

Now that we have registered the Bean of the custom agent with the Spring container, let's test how the Bean of this agent is called.

1. Define spring-config.xml

Here we configure RegisterBeanFactory into the xml configuration of spring to facilitate loading at startup. two。 Unit Test @ Test

Public void test_IUserDao () {

BeanFactory beanFactory = new ClassPathXmlApplicationContext ("spring-config.xml")

IUserDao userDao = beanFactory.getBean ("userDao", IUserDao.class)

String res = userDao.queryUserInfo ()

Logger.info ("Test results: {}", res)

}

"Test results"

22 Could not find key 53 spring.liveBeansView.mbeanDomain' in any property source 14. 759 [main] DEBUG o.s.c.e.PropertySourcesPropertyResolver-Could not find key'

22 Returning cached instance of singleton bean 53 14. 760 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory-Returning cached instance of singleton bean 'userDao'

22 main 53 14. 796 [main] INFO org.itstack.interview.test.ApiTest-Test result: you are represented by queryUserInfo

Process finished with exit code 0

As you can see from the test results, we have been able to achieve our expected results by injecting the proxy Bean object into Spring. In fact, this process is also used in many frameworks, especially in some middleware development, similar ORM frameworks need to be used. "how to tuck Bean into a Spring container" is introduced here, thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report