Blog: bugstack.cn

Precipitation, share, grow, let yourself and others can gain something! 😄

One, foreword

How do you study, Little Fu?

A lot of people who are new to programming or who have been coding CRUD bricks for a few years ask me, how should I learn to program? What if you feel like you can’t do anything? I feel that my current company has no core business to learn.

In fact, I probably have similar experience with a large number of fans and readers. I have been in the traditional outsourcing industry, started from C# language development for two years and then started to work in Java, and I feel that I am new to the Internet job market.

But probably the thing that helped me the most about learning to program was playing around with these techniques:

  1. About outsourcing: during the two years of outsourcing, I was still developing C#, sometimes working on repeater, IO board card and PLC. But I still like the Java language I learned in college, so every day at 5:30 when I go home from work, I constantly use the Java language to update the C# project that the company came into contact with. It took me almost a year to renovate all the projects I touched. It was interesting to know that Java could do serial communication at that time.
  2. On the scene: In fact, many programmers in a relatively small company, learning the biggest bottleneck is the problem of vision, do not know what technology, do not know what the scene, do not know what they do not know. In fact, a lot of times it’s likelazyYes, the company does not have such a scene, but you can see blogs, forums, videos, plus various technical groups. If encounter what advertisers departed, what good stay, know some connections, to know some gay friends, can always learn it in the process, you will smell of various technology stack as time goes on, project, experience, insight, interview and so on, when you armed themselves, are not so difficult also to go out for an interview.
  3. About the beginning: Less time, more to learn, feel like a handfulSmall shovelI’m going to dig the Suez Canal. I don’t know where to start. At this time, it is recommended not to blindly collect several T’s materials and videos. First, open XMind, select a nice topic, and start sorting out your own technology stack to see what you know and what you don’t know. Then, select what you want to learn from the contents you don’t know, and sort out the corresponding database of the contents you want to learn. Ok, so this is the time to start, remember to start small, don’t always want to eat fat.

In the right direction, fast is the biggest obstacle! Most of the time as long as you can calmly accumulate over a long period of time learning, in fact, there is no problem that can not be overcome. Is there anything very difficult in programming? Most of the knowledge is not to know, it is very easy to know.

2. Interview questions

Thanks for the plane, note! I’ve mastered everything on my resume. 20K is fine. Just wait!

Interviewer: thank plane, technology is good ah, are proficient, oh, there is a VB understanding, nothing we do not use VB

Thank plane: return line, I learn of much, you ask.

Interviewer: Well, a lot of confidence. Well, let’s talk about Spring. You’re pretty good at that, too.

Xie Airplane: Come on!

Interviewer: How do you stuff beans into the Spring container? Can you talk a little bit about the process, have you used the technology, what kind of scenarios?

Xie Airplane: HMM! ? Well, I don’t think so. I’m pretty proficient with the API, @Resource

Interviewer: Oh, @Resource, which module of Spring provides annotations?

Xie Airplane: me, goodbye! ヾ( ̄▽ ̄)

The proxy Bean is registered with the Spring container

  • In terms of technical scenarios for Bean registration, MyBatis is the most common of the technical frameworks we use every day. MyBatis only defines an interface without writing the implementation class, but this interface can be associated with the configured SQL statement, and the corresponding database operation can return the corresponding results. The interface and database operations then use the Bean’s proxy and registration.
  • As we all know, class invocation cannot directly call the interface without implementation, so we need to generate the corresponding implementation class for the interface by proxy. This is then done by putting the proxy class into Spring’s FactoryBean implementation, and finally registering the FactoryBean implementation class with the Spring container. Your proxy class is now registered with the Spring container and can then be annotated into properties.

With this implementation in mind, let’s take a look at how a Bean’s registration process is implemented in code.

1. Define interfaces

public interface IUserDao {

    String queryUserInfo(a);

}
Copy the code
  • First define a DAO like interface, basically such interface is very common when using MyBatis. We will proxy and register this interface later.

2. Class proxy implementation

ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Class<? >[] classes = {IUserDao.class}; InvocationHandler handler = (proxy, method, args) ->"You're being represented." + method.getName();
IUserDao userDao = (IUserDao) Proxy.newProxyInstance(classLoader, classes, handler); 

String res = userDao.queryUserInfo();
logger.info("Test result: {}", res);
Copy the code
  • Java’s own proxy approach is relatively simple to use and fairly fixed in usage.
  • InvocationHandler is an interface class whose corresponding implementation content is the concrete implementation of the proxy object.
  • The last thing is to give the Proxy to the Proxy and create the Proxy object,Proxy.newProxyInstance.

3. Implement Bean factories

public class ProxyBeanFactory implements FactoryBean {

    @Override
    public Object getObject(a) throws Exception {

        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        Class[] classes = {IUserDao.class};
        InvocationHandler handler = (proxy, method, args) -> "You're being represented." + method.getName();

        return Proxy.newProxyInstance(classLoader, classes, handler);
    }

    @Override
    publicClass<? > getObjectType() {returnIUserDao.class; }}Copy the code
  • A FactoryBean plays a secondary role in Spring. It has more than 70 children (the interface definition that implements it), so it has three methods;
    • T getObject() throws Exception; Returns the bean instance object
    • Class
      getObjectType(); Returns the instance class type
    • boolean isSingleton(); Check whether singletons are placed in the Spring container’s singleton cache pool
  • Here we put the Java proxy object above into the getObject() method, and now the object we get from Spring is our proxy object.

4. Register beans

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); }}Copy the code

In the Spring Bean management, all of the beans can eventually be registered to the class DefaultListableBeanFactory, this part of the code above the main content includes:

  • Implement BeanDefinitionRegistryPostProcessor postProcessBeanDefinitionRegistry method, obtain the Bean registered object.
  • Define the Bean, GenericBeanDefinition, where we mainly set up our proxy class factory.
  • Create Bean definition processing class, BeanDefinitionHolder, the main argument needed here; Define beans and namessetBeanClass(ProxyBeanFactory.class).
  • Finally we own bean registered in the spring container, registry. RegisterBeanDefinition ()

4. Test and verification

Now that we have registered the custom proxy Bean with the Spring container, let’s test how the proxy Bean is called.

1. Define the spring – config. XML

<bean id="userDao" class="org.itstack.interview.bean.RegisterBeanFactory"/>
Copy the code
  • Here we configure the RegisterBeanFactory into the Spring XML configuration for easy loading at startup.

Unit testing

@Test
public void test_IUserDao(a) {
    BeanFactory beanFactory = new ClassPathXmlApplicationContext("spring-config.xml");
    IUserDao userDao = beanFactory.getBean("userDao", IUserDao.class);
    String res = userDao.queryUserInfo();
    logger.info("Test result: {}", res);
}
Copy the code

The test results

22:53:14.759 [main] DEBUG o.s.c.e.PropertySourcesPropertyResolver - Could not find key 'spring.liveBeansView.mbeanDomain' in any property source
22:53:14.760 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'userDao'
22:53:14.796[the main] INFO org. Itstack. Interview. Test. The ApiTest - test results: you have the agent queryUserInfo Process finished with exit code0
Copy the code
  • From the test results, we can already achieve our expected results with the proxy Bean object injected into Spring.
  • In fact, this process is also used in many frameworks, especially in some middleware development, similar ORM frameworks need to use.

Five, the summary

  • The content of this section is relatively uncomplicated, but this section of code is the core flow that we have extracted from the source code learning, because this is basically the same process in most frameworks. If you don’t, it’s hard to read the source code of a framework like this and understand how it’s called.
  • The main technical points involved in this paper include; Proxy, object, registration, and corresponding usage. In particular, the definition of beansBeanDefinitionHolderAnd Bean registrationBeanDefinitionReaderUtils.registerBeanDefinition.
  • If you can relate more to this technique, try replacing the proxy object with the database query object, i.e. the JDBC operation, and when you are done you will have implemented a simple ORM framework. In fact, many technical implementations are made from small to large, but the initial part is the core of the entire code implementation.

Six, series recommendation

  • Recognize your technology stack blind spots
  • LinkedList inserts faster than ArrayList? Are you sure?
  • In addition to JDK and CGLIB, there are three kinds of proxy methods. The interview is stuck again!
  • AQS principle analysis and practical use of ReentrantLock
  • Zha? Your IDEA has expired. Add a Jar package to crack, why?