This is my 24th day of the Gwen Challenge

Spring source code

1. Source code compilation (first look at 5 compile error summary, then 4, and then encountered error registration)

Idea: 2018 (later changed to 2020)

Gradle: 4.9

Spring – framework5.0. X

(For 5.0.x only, not sure for other versions)

  1. Download source: github.com/spring-proj…

  2. Import project using IDEA:

1. Mistake 1:

Comment out using the original development environment

2. Question 2:

Lack of jars

3. Question 3

CompileTestJava gradlew :spring-oxm:compileTestJava gradlew :spring-core:compileTestJava builds successfully, but there is still a problem when importing idea:

Later, the version is changed to 4.9, and this getArchiveFile problem occurs again

Gradle, gradle.properties, settings.gradle.

Modified as follows:

settings.gradle

pluginManagement {
	repositories {
		maven { url 'https://maven.aliyun.com/repository/gradle-plugin' }  / / ali cloud
		maven { url 'https://maven.aliyun.com/repository/spring-plugin'}   //
		maven { url "https://maven.aliyun.com/repository/public" }         //
		maven { url "https://maven.aliyun.com/repository/central" }        //
		gradlePluginPortal()
		maven { url 'https://repo.spring.io/plugins-release' }
	}
}

plugins {
	id "com.gradle.enterprise" version "3.2"
	id "io.spring.gradle-enterprise-conventions" version "Hundreds"
}
Copy the code

build.gradle

resolutionStrategy {
	cacheChangingModulesFor 0."seconds"
}
repositories {
	maven { url "https://maven.aliyun.com/repository/apache-snapshots" }
	maven { url "https://maven.aliyun.com/repository/spring" }
	maven { url "https://maven.aliyun.com/repository/google" }
	maven { url 'https://maven.aliyun.com/repository/central'}
	maven { url "https://maven.aliyun.com/repository/public" }
	mavenCentral()
	maven { url "https://repo.spring.io/libs-spring-framework-build"}}Copy the code

gradle.properties

## where you need to correspond to your own version version=5.32.Org.gradle. jvmargs= -xmx2048m ## Enable org.gradle.caching=true## Open org.gradle.parallel=true# # to enable new incubator model org. Gradle. Configureondemand =trueBy enabling the daemon, the next build will connect to the daemon instead of forking the gradle build process org.gradle.daemon=true
Copy the code

Finally, I downloaded 5.0.19.zip in git release, but not 5.0.x version. Then I directly decompressed and imported it, annotated the compiled environment, which was mentioned in error 1, and compiled as follows :(I don’t know whether the compilation was successful or not)

The compilation process took me nearly an hour.

Then run spring-core and get the following error:

Solution: Run the following command in terminal of idea:

gradle objenesisRepackJar
gradle cglibRepackJar
Copy the code

Error :(video explanation: ignore)

Compile the spring aop

Error :(no problem)

Testing:

Create a Gradle module

Similar to creating a Spring project

Configuration depends on

gradle

dependencies {
    compile(project(":spring-context")) // Add dependencies
}
Copy the code

Then reference the directory of files in Spring-test to build your own test project

Then right-click to build, as shown below:

Then in the class to add annotations, found the annotation error, unable to resolve, and rebuild the project, found this wrong

Because Spring relies on the AspectJ package, you need to install it

Aspectj-1.9.2.jar (eclipse.org)

Then install, download and install the spring source, import the idea and the detailed solutions to problems compiler error process _a704397849 blog – CSDN blog] (blog.csdn.net/a704397849/…).

Make sure both plug-ins are installed before doing so

  1. Spring AOP/@AspectJ
  2. AspectJ Support

For their own convenience, they took pictures of the bloggers

Then build project, also error,

This error can be ignored for now, the package problem is resolved. However, there is still no @repository annotation for your own projects. Then use Alt + Enter to select the spring-context-main package, and then it is done, but the image is not captured, and the subsequent replay is not successful. Maven-like adding dependency packages. I’ve captured an imported package and can try importing it manually

Then use AnnotationConfigApplicationContext variable CTX call register red, error, forgot to capture (all going crazy) can’t use classes remember wrong wrong or can’t find the spring – under the context of what package.

4. Recompile

  1. Download source code: the above address

  2. Change the gradle-wrapper.properties configuration under Spring-Framework-5.0.x \gradle\wrapper to use local gradle

    distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME ZipStorePath =wrapper/dists # change your local package to save each build download, too slow distributionUrl=file:/ / / E: / My_File_Code/Source_Study/Spring - 5-0 - x/gradle - 4.9 - bin. Zip
    #distributionUrl=https\:/ / services.gradle.org/distributions/gradle-4.4.1-bin.zip
    
    Copy the code
  3. Modify the build. Gradle

    repositories {
        maven { url 'https://maven.aliyun.com/nexus/content/groups/public/' }
        maven { url 'https://maven.aliyun.com/nexus/content/repositories/jcenter' }
        gradlePluginPortal()
        maven { url "https://repo.spring.io/libs-spring-framework-build" }
        maven { url "https://repo.spring.io/milestone"} # Spring plugin maven {url"https://repo.spring.io/plugins-release"}}Copy the code
  4. Error: Run gradlew. Bar in CMD

    Solution:

  5. Compile and run gradlew. Bat again in CMD, successful

  6. According to the official documentation: import-into-idea.md operation (but some tutorials say you can not operate, directly import). I’ll stick to the documentation

    #Precompile spring-OXM Spring-core
    gradlew :spring-oxm:compileTestJava
    gradlew :spring-core:compileTestJava
    Copy the code

Error: Gradle version is higher than 5.0. I don’t know where I can change Gradle version.

Then suddenly found a description in CSDN bbs.csdn.net/topics/3947…

In spring-beans.gradle, modify the next three parts as follows:

spring-beans.gradle

compileGroovy {
	sourceCompatibility = 1.8
	targetCompatibility = 1.8
	options.compilerArgs += "-Werror"
}

// This module also builds Kotlin code and the compileKotlin task naturally depends on
// compileJava. We need to redefine dependencies to break task cycles.
// compileKotlin.dependsOn(compileGroovy)
// Add these
def deps = compileGroovy.taskDependencies.immutableValues + compileGroovy.taskDependencies.mutableValues
compileGroovy.dependsOn = deps - "compileJava"
compileKotlin.dependsOn(compileGroovy)
compileKotlin.classpath += files(compileGroovy.destinationDir)
Copy the code

Then I run it again in CMD. I failed 7 times before I finally succeeded. Some of his packages could not be downloaded, so I failed. Be patient.

(Or try: and then according to the online said, directly import idea, the previous import process has already been described, no longer.)

Then import IDEA, as for the configuration before also talked about, do not narrate.

Then it’s just a matter of waiting. Error reported after half an hour: network reasons (suggest 6 am more up to compile, the feeling will be faster, or do not compile at night) see that 5 or 6 minutes to compile, I am very desperate

Because of the speed of the network, I reloaded it many times, 8-9 hours, and it was crazy. Compile succeed, but in the build – gradle DependencyResolveDetails, according to the prompt because gradle – API – 4.9 didn’t import the jar, then gradle – API – 4.9. Jar (gradle installation directory, Can search package name) import can. Project Structure- library Click Add, this should work. After import, reload, resolve.

Next, start compiling the Spring-OXM module

After that, spring-context, spring-bean, is compiled in the same way as spring-OXm. There’s no problem here

Next, compile Spring-AOP. As mentioned earlier, aspecJT is required to compile AOP. How to add it has already been mentioned and will not be repeated. Then compile similar to the previous steps. No more texturing.

Open the spring-Aspecjt module, SRC – “test-” Java, right-click Java, and click Run test….. Can also compile)

Five minutes later the compilation is complete

Add module tests: The steps are no longer described. After this adds dependent AnnotationConfigApplicationContext cannot access packet call didn’t happen.

The code block is as follows:

appconfig.java

@Configuration
@ComponentScan("com.anzhi")
public class Appconfig {}Copy the code

IndexDao.java

@Repository
public class IndexDao {
	public void query(a){
		System.out.println("querry"); }}Copy the code

TestSpring.java

public class TestSpring {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext ctx =
				newAnnotationConfigApplicationContext(Appconfig.class); IndexDao indexDao = ctx.getBean(IndexDao.class); indexDao.query(); }}Copy the code

build.gradle

Compile (project(":spring-context")) testCompile group: 'junit', name: 'junit', version: '4.12'}Copy the code

The results are as follows:

5. Summary of compilation errors

  1. Run gradlew. Bat to run gradlew. Bat to run gradlew. Bat to run gradlew. (Try not to include Chinese path or space, god knows what might be wrong)
  2. Precompiling from documents causes errors like this:
    1. GetArchiveFile cannot be found, symbol error, required Spring-core, bean, etc. However, the strange thing is that after I re-downloaded and compiled, neither of these conditions appeared in the process, and I did not even find the method getArchiveFile. Also speechless. You can avoid this, however, if there is a network problem with the compile and download, or if the spring-Beans configuration is not just a simple comment, it may include a “I configured” sentence (also accidentally found on the Internet). .
  3. Spring-aspejct requires the ASpejCT compilation tool to ensure that the plug-ins for IDEA are complete (as mentioned earlier, Kotlin and Gradle are added). It is also important to note that the IDEA should be raised as much as possible. I always feel that there are problems with the plug-ins in 2018, which have not been verified. I upgraded to the 2020 version.
  4. And then like what Annotation… Can’t find, symbol error, etc., after the front is done, basically there will be no problem.
    1. Still encounter a problem, can consult these a few websites to try
    2. Gradle builds Spring5 source code reading environment tutorial (optimize build speed) – Jihu.com
    3. I heard that you were discouraged from source code compilation before you could learn Spring? 30+ images to take you through Spring compilation
    4. How to compile Spring source code
    5. Spring5.3.x source code reading environment construction – small black computer
    6. Document several potholes in compiling spring-framework source code
    7. Build Spring – Simple book
    8. Gradle compile Spring source code – but do good – don’t ask future – blog garden
    9. Spring5 source code reading environment build – Gradle build build _zhoong-CSDN blog
    10. Spring5 source code compiled _chuyang0312 blog -CSDN blog
    11. Spring learning -01 compiler Spring 5.0 source code (pro test available) _ quiet little seal blog -CSDN blog
  5. Another option is to go to Gitee and look for applications compiled by others, not necessarily by yourself. Alas, build build environment what good, this life is impossible to build build environment again.

2. Simulate spring source code

Creating a New Maven Project

Dao layer

UserDao.java

package dao;

public interface UserDao {
    public void query(a);
}
Copy the code

UserDaoImpl.java

package dao;

public class UserDaoImpl implements UserDao{
    @Override
    public void query(a) {
        System.out.println("service"); }}Copy the code

The service layer

UserService.java

package service;

public interface UserService {

    public void find(a);
}
Copy the code

UserServiceImpl.java

package service;

import dao.UserDao;

public class UserServiceImpl implements UserService{

    UserDao userDao;


    @Override
    public void find(a) {
        System.out.println("service"); userDao.query(); }}Copy the code

Create a Test class Test

package test; import service.UserService; import service.UserServiceImpl; public class Test { public static void main(String[] args) { UserService service = new UserServiceImpl(); service.find(); }}Copy the code

The null pointer exception is found because the userDao is not associated with the Service and the Query depends on the userDao under the DAO package.

So you need to add dependencies. If you’re a Spring company, how do you develop?

  1. Which classes need dependencies, and how do I tell the compiler that these classes are needed? Bean label

  2. How do you assign the userDAO class to a service when you have a dependency?

    1. Provide set/get methods
    2. Construction time supply
  3. But this method is implemented by programmers themselves, without relying on third parties. Relying on third-party implementations is called injection. The set/ construct, however, is not so smart for the container that we need to tell it which method to inject.

  4. How do you maintain dependencies after that? setter/structure

  5. So how do I volume setter/structure. The property tag

  6. After adding the property, you eventually need to give the class to the service in its entirety through a third party. How?

    The following code is implemented:

    package utils;
    
    import org.dom4j.Attribute;
    import org.dom4j.Document;
    import org.dom4j.DocumentException;
    import org.dom4j.Element;
    import org.dom4j.io.SAXReader;
    
    import java.io.File;
    import java.io.UnsupportedEncodingException;
    import java.lang.reflect.Field;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
    
    public class BeanFactory {
    
    
        // Use map to store objects, just a simple simulation, more data types are not extended here
        Map map = new HashMap<String,Object>(); 
    
        public BeanFactory(String xml) throws Exception{
            paresXml(xml);
        }
    
        /* * * parse the XML file * */
        private void paresXml(String xml) throws Exception{
    
            /* * File path source * */
    
            String configPath = this.getClass().getResource("/").getPath()+"/ /"+xml;
            try {
                /* * Solve the problem of Chinese garble * */
                configPath =  java.net.URLDecoder.decode(configPath,"utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            File file = new File(configPath);
            /* * Dom4j utility classes use * */
            SAXReader reader = new SAXReader();
    
                Document document = reader.read(file);
                Element rootElement = document.getRootElement();
    
                /* * iterate over each element and place it in the Map * */
                for(Iterator<Element> itFirlst = rootElement.elementIterator(); itFirlst.hasNext();) {/* * 1. Instantiate the object, which implements parsing of the child tags under each parent tag * */
                    Element elementFirstChil = itFirlst.next();
                    Attribute attributeId = elementFirstChil.attribute("id");
                    String beanId = attributeId.getValue();
                    Attribute attributeClass = elementFirstChil.attribute("class");
                    String clazzName = attributeClass.getValue();
                    Class clazz = Class.forName(clazzName);;
                    Object object = clazz.newInstance();
    
    
                    /* * Maintains dependencies * to see if the object has dependencies, whether it has properties, or whether the class has properties * if injected * */
    
                    for(Iterator<Element> itSecond = elementFirstChil.elementIterator(); itSecond.hasNext();) {/* * <bean id="service" class="service.UserServiceImpl"> * <! Setname = setName = setName = setName = setName = setName = setName = setName = setName = setName = setName = setName = setName = setName = setName = setName = setName = setName = setName = setName = setName = setName = setName
                        Element elementSecondChil = itSecond.next();
                        if(elementSecondChil.getName().equals("property")){
                            String refValue = elementSecondChil.attribute("ref").getValue();
                            Object injetObject = map.get(refValue);
                            String nameValue = elementSecondChil.attribute("ref").getValue();
                            Field field = clazz.getDeclaredField(nameValue);
                            field.setAccessible(true);
                            field.set(object,injetObject);
                        }
                    }
    
                    Field[] fields = clazz.getDeclaredFields();
                    for(Field field:fields){
    
                    }
                    map.put(beanId, object);
                }
            System.out.println(map);
    
        }
    
        public Object getBean(String name){
            returnmap.get(name); }}Copy the code

    Test.java

    package test;
    
    import service.UserService;
    import utils.BeanFactory;
    
    public class Test {
        public static void main(String[] args) throws Exception{
    
            BeanFactory beanFactory = new BeanFactory("spring.xml");
    
            //UserService service = new UserServiceImpl();
            UserService service = (UserService) beanFactory.getBean("service"); service.find(); }}Copy the code

    The spring XML configuration

    
            
    <beans>
    
        <bean id="userDao" class="dao.UserDaoImpl"></bean>
        <bean id="service" class="service.UserServiceImpl">
            <! --setter-->
            <property ref="userDao"></property>
        </bean>
    </beans>
    Copy the code

    Same type injection (error message)

    BeanFactory.java

    package utils;
    
    import org.dom4j.Attribute;
    import org.dom4j.Document;
    import org.dom4j.DocumentException;
    import org.dom4j.Element;
    import org.dom4j.io.SAXReader;
    
    import java.io.File;
    import java.io.UnsupportedEncodingException;
    import java.lang.reflect.Constructor;
    import java.lang.reflect.Field;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
    
    public class BeanFactory {
    
    
        Map<String,Object> map = new HashMap<String,Object>();
    
        public BeanFactory(String xml) throws SpringException{
            paresXml(xml);
        }
    
        /* * * parse the XML file * */
        private void paresXml(String xml) throws SpringException{
    
            /* * File path source * */
    
            String configPath = this.getClass().getResource("/").getPath()+"/ /"+xml;
            /* * Solve the problem of Chinese garble * */
            try {
                configPath =  java.net.URLDecoder.decode(configPath,"utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
    
            File file = new File(configPath);
            /* * Dom4j utility classes use * */
            SAXReader reader = new SAXReader();
    
            Document document = null;
            try {
                document = reader.read(file);
            } catch (DocumentException e) {
                e.printStackTrace();
            }
            Element rootElement = document.getRootElement();
            Attribute attribute = rootElement.attribute("default");
            boolean flag = false;
            if(attribute ! =null){
                flag = true;
            }
            /* * iterate over each element and place it in the Map * */
            for(Iterator<Element> itFirlst = rootElement.elementIterator(); itFirlst.hasNext();) {/* * 1. Instantiate the object, which implements parsing of the child tags under each parent tag * */
                Element elementFirstChil = itFirlst.next();
                Attribute attributeId = elementFirstChil.attribute("id");
                String beanName = attributeId.getValue();
                Attribute attributeClass = elementFirstChil.attribute("class");
                String clazzName = attributeClass.getValue();
                Class clazz = null;
                try {
                    clazz = Class.forName(clazzName);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
    
    
                /* * 2. Maintain dependencies * see if the object has dependencies, check whether there is a property, or check whether the class has properties * if there is injection * */
                Object object = null;
                for(Iterator<Element> itSecond = elementFirstChil.elementIterator(); itSecond.hasNext();) {/* * <bean id="service" class="service.UserServiceImpl"> * <! Setname = setName = setName = setName = setName = setName = setName = setName = setName = setName = setName = setName = setName = setName = setName = setName = setName = setName = setName = setName = setName = setName = setName
                    Element elementSecondChil = itSecond.next();
                    if(elementSecondChil.getName().equals("property")) {// Since it is a setter, there is no special constructor, so it can only be used directly
                        try {
                            object = clazz.newInstance();
                        } catch (Expection e) {
                            e.printStackTrace();
                        }
                        String refValue = elementSecondChil.attribute("ref").getValue();
                        Object injetObject = map.get(refValue);
                        String nameValue = elementSecondChil.attribute("ref").getValue();
                        System.out.println(nameValue);
                        Field field = null;
                        try {
                            field = clazz.getDeclaredField(nameValue);
                            field.setAccessible(true);
                            field.set(object,injetObject);
                        } catch(Exception e) { e.printStackTrace(); }}else{
                        // Show that there is a special constructor injection
                        String refVlaue = elementSecondChil.attribute("ref").getValue();
                        Object injetObject= map.get(refVlaue) ;
                        Class injectObjectClazz = injetObject.getClass();
                        Constructor constructor = null;
                        try {
                            constructor = clazz.getConstructor(injectObjectClazz.getInterfaces()[0]);
                            object = constructor.newInstance(injetObject);
                        } catch(Exception e) { e.printStackTrace(); }}}if(object==null) {if(flag){
                        if(attribute.getValue().equals("byType")) {// Determine whether there are dependencies
                            Field[] declaredFields = clazz.getDeclaredFields();
                            for(Field field:declaredFields){
                                // Get the type of the attribute, such as String ass, then field.getType()= string.class;
                                Class inObjectClazz = field.getType();
                                InObjectClazz (int int, int int, int int, int int, int int, int int)
                                int count= 0;
                                Object injectObjec = null;
                                for (String key : map.keySet()) {
                                    Class temp = map.get(key).getClass().getInterfaces()[0];
                                    if(temp.getName().equals(inObjectClazz.getName()) ){
                                        injectObjec = map.get(key);
                                        // Record to find one, as multiple can be foundcount++; }}// Find two conflicts and throw an exception
                                if(count>1) {throw new SpringException("Need one object, but find two objects.");
                                }else{
                                    try {
                                        object = clazz.newInstance();
                                        field.setAccessible(true);
                                        field.set(object, injectObjec);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                    }
                }
    
                if(object==null) {// No child tags
                    try {
                        object = clazz.newInstance();
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
                map.put(beanName, object);
            }
            System.out.println(map);
    
        }
    
        public Object getBean(String name){
            returnmap.get(name); }}Copy the code

Summary:

  1. Iterating through the configuration file, the scanned class name is reflected into the Map collection, i.e. Class.forname () instantiates the object;
  2. Dependency injection: Determines whether an object has attributes and infuses them if it does

(3) simulate the annotation

The BeanFactory and FactoryBean:

  1. If your class implements a FactoryBean, there are two objects in the Spring container, one for getObject(), the returned object, and one for the current object.

    Obtain beanName by name. There are two reasons not to use name as a beanName: Name might start with an & character, indicating that the caller wants to get the FactoryBean itself, not the bean created by the FactoryBean implementation class.

  2. Application Scenarios:

    When a class has many attributes and depends on many, even some classes that rely on third-party libraries, there are so many attributes that it explodes. If you have to maintain them, how do you maintain them? Take Mybatis

    Introduce SqlSessionFactory through XML configuration,

    
            
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
        <bean id="SqlSessionFactory" class="SqlSessionFactory">
        	<property></property>
            <property></property>.</bean>
        
        
        <bean id="dao" ref="SqlSessionFactory"></bean>
        <! There is no way for Mybatis to change its config file, even if you can tolerate it.
    </beans>
    Copy the code

    Hence the SqlSessionFactoryBean, which implements the methods of the FactoryBean interface to help with configuration.

    This can be simulated simply:

    package dao;
    
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.ImportResource;
    
    @Configuration
    @ComponentScan("dao")
    @ImportResource("classpath:springapplication.xml")
    public class TempDaoFactoryBean {
    
        private String msg;
        private String msg2;
        private String msg3;
    
        public void testBean (a) {
            System.out.println("FactoryBean");
        }
    
    
        public String getMsg(a) {
            return msg;
        }
    
        public void setMsg(String msg) {
            this.msg = msg;
        }
    
        public String getMsg2(a) {
            return msg2;
        }
    
        public void setMsg2(String msg2) {
            this.msg2 = msg2;
        }
    
        public String getMsg3(a) {
            return msg3;
        }
    
        public void setMsg3(String msg3) {
            this.msg3 = msg3;
        }
    
        @Override
        public String toString(a) {
            return "TempDaoFactoryBean{" +
                    "msg='" + msg + '\' ' +
                    ", msg2='" + msg2 + '\' ' +
                    ", msg3='" + msg3 + '\' ' +
                    '} '; }}Copy the code
    package dao;
    
    import org.springframework.beans.factory.FactoryBean;
    import org.springframework.context.annotation.Bean;
    import org.springframework.stereotype.Component;
    
    /*@Component("daoFactoryBean")*/
    public class DaoFactoryBean implements FactoryBean{
        private String msg;
    
        public void testBean(a){
            System.out.println("daoFactoryBean");
        }
    
        @Override
        public Object getObject(a) throws Exception {
            TempDaoFactoryBean temp = new TempDaoFactoryBean();
            String[] msgArray = msg.split(",");
            temp.setMsg(msgArray[0]);
            temp.setMsg2(msgArray[1]);
            temp.setMsg3(msgArray[2]);
    
            return temp;
        }
    
        @Override
        publicClass<? > getObjectType() {return TempDaoFactoryBean.class;
        }
    
        @Override
        public boolean isSingleton(a) {
            return true;
        }
    
        public void setMsg(String msg) {
            this.msg = msg; }}Copy the code

    springapplication.xml

    
            
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
        <bean id="TempDaoFactoryBean" class="dao.DaoFactoryBean" >
            <property name="msg" value="msg,msg2,msg3"></property>
        </bean>
    </beans>
    Copy the code

Summary: With the above two exercise codes can be concluded:

BeanFactory does not belong to the Spring container. It can create a bean object. A FactoryBean is itself a bean object that belongs to Spring, and this bean object can be created by getObject. This verifies that we wanted to get cc from Spring, but we actually got &cc, because getObject is itself a bean object.

1. There are several ways to initialize the Spring environment

  1. XML: ClassPathXmlApplicationContext (finishing class scanning, can complete separate bean registration, namely the declaration and registration)

  2. Annotation: Spring does not recognize annotation scanning unless it depends on 1 or 2

  3. Scanning javaconfig: AnnotationConfigApplicationContext (same finish class, class definition, but there is no class of registration)

    Initializing the Spring environment ——- is about handing programmers over to spring-managed classes to instantiate

    Demonstrate 3:

    Appconfig.java

    package config;
    
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    
    public class Appconfig {}Copy the code
    package service;
    
    
    import org.springframework.stereotype.Service;
    
    @Service
    public class TestService {}Copy the code
    package test;
    
    import config.Appconfig;
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    import service.TestService;
    
    public class TestServiceDefinition {
        public static void main(String[] args) {
            AnnotationConfigApplicationContext ctx =
                    new AnnotationConfigApplicationContext(Appconfig.class);
    
            / / because just declare TestService, but is not defined, not to be found so in the end, NoSuchBeanDefinitionExceptionSystem.out.println(ctx.getBean(TestService.class).getClass().getName()); }}Copy the code

    Appconfig.java

    @ComponentScan("com.anzhi")
    Copy the code

    TestServiceDefinition.java

    AnnotationConfigApplicationContext ctx =
        new AnnotationConfigApplicationContext();
    
    // Register can register two types of beans. The first type is Configuration beans, which are plain beans
    // Then scan ComponentScan again in Appconfig
    // Refresh is not called under register
    ctx.register(Appconfig.class);
    // So you need to manually refresh. @profile instantiates the object first and then sets the object properties
    // So we can write this again
    ctx.refresh();
    Copy the code
    AnnotationConfigApplicationContext ctx =
        new AnnotationConfigApplicationContext(); // If all classes are scanned at the beginning, then // ctx.getenVironment ().setActiveProfiles(); It doesn't work
    //setting Sets the condition
    ctx.getEnvironment().setActiveProfiles();
    // Register can register two types of beans. The first type is Configuration beans, which are plain beans
    // Then scan ComponentScan again in Appconfig
    // Refresh is not called under register
    
    // Then when scanning here, instead of scanning all classes part
    ctx.register(Appconfig.class);
    // So you need to manually refresh. @profile instantiates the object first and then sets the object properties
    // So we can write this again
    ctx.refresh();
    Copy the code

    The second type, monoclass

    package com.anzhi.config;
    
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    //@ComponentScan("com.anzhi")
    public class Appconfig {}Copy the code

    TestServiceDefinition.java

    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx =
            new AnnotationConfigApplicationContext();
    
        ctx.getEnvironment().setActiveProfiles();
    
        // Register can register two types of beans. The first type is Configuration beans, which are plain beans
        // Then scan ComponentScan again in Appconfig
        ctx.register(Appconfig.class);
        // ctx.register(TestService.class); // The second type, single-class registration
        ctx.ctx.scan("com");
        ctx.refresh();
        System.out.println(ctx.getBean(TestService.class).getClass().getName());
    
    }
    Copy the code

2. Anno

AnnotationConfigApplicationContext.java

package com.anzhi.utils;

import com.anzhi.anno.AnnoAnzhi;

import javax.xml.bind.Element;
import java.io.File;
import java.lang.reflect.Field;

public class AnnotationConfigApplicationContext {

    public void scan(String basePackage){

        // Get the path of the class
        String path = this.getClass().getResource("/").getPath();
        String basePackagePath = basePackage.replaceAll("\ \."."\ \ \ \");
        try {

            path = java.net.URLDecoder.decode(path, "UTF-8");

            File file = new File(path + "/ /" + basePackagePath);

            String[] namePath = file.list();

            for (String name : namePath){
                name = name.replaceAll(".class"."");
                Class clazz = Class.forName(basePackage+"."+name);
                // Check whether it belongs to @xxxx
                if(clazz.isAnnotationPresent(AnnoAnzhi.class)){ AnnoAnzhi anzhi = (AnnoAnzhi) clazz.getAnnotation(AnnoAnzhi.class); System.out.println(anzhi.value()); System.out.println(clazz.newInstance()); }}}catch(Exception e){ e.printStackTrace(); }}}Copy the code

TestAnnoAnzhi.java

package com.anzhi.test;

import com.anzhi.utils.AnnotationConfigApplicationContext;

public class TestAnnoAnzhi {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx =
                new AnnotationConfigApplicationContext();

        ctx.scan("com.anzhi.service"); }}Copy the code

(Annotate @autowired if you have time.)