spring IOC 简易实现

1、自己实现一个ioc容器,在idea中创建maven-web项目spring10

2、配置文件文件如下:
pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.ayb</groupId>
  <artifactId>spring1.0</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>spring1.0 Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.0.1</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>

  <build>
    <finalName>spring1.0</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

web.xml
 

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <display-name>Archetype Created Web Application</display-name>
    <servlet>
        <servlet-name>mvc</servlet-name>
        <servlet-class>servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:application.properties</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>mvc</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>

</web-app>

application.properties文件:
 

scanPackage=demo

3、先创建与web相关的5个注解类:
 

package servlet.annotation;

import java.lang.annotation.*;

@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {
    String value() default "";
}
package servlet.annotation;

import java.lang.annotation.*;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Controller {
    String value() default "";
}
package servlet.annotation;

import java.lang.annotation.*;

@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestMapping {
    String value() default "";
}
package servlet.annotation;

import java.lang.annotation.*;

@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestParam {
    String value();
}
package servlet.annotation;

import java.lang.annotation.*;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Service {
    String value() default "";
}

4、创建核心控制器类DispatcherServlet
 

package servlet;

import servlet.annotation.Autowired;
import servlet.annotation.Controller;
import servlet.annotation.Service;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
//Servlet只是作为mvc的启动入口
public class DispatcherServlet extends HttpServlet {
    private Properties contextConfig= new Properties();
    private Map<String,Object> beanMap=new ConcurrentHashMap<String,Object>();
    private List<String> classNames=new ArrayList<>();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }

    @Override
    public void init(ServletConfig config) throws ServletException {

        //定位
        doLoadConfig(config.getInitParameter("contextConfigLocation"));

        //加载
        doScanner(contextConfig.getProperty("scanPackage"));

        //注册
        doRegistry();

        //自动注入
        //在spring中,通过getBean方法来触发注入
        doAutowired();

        //springmvc需要初始化处理器映射器
        initHandlerMapping();

    }



        //定位
        private void doLoadConfig(String location){
            //spring中通过reader去查找和定位
            InputStream is=this.getClass().getClassLoader().getResourceAsStream(location.replace("classpath:",""));
            try {
                contextConfig.load(is);
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    if(null!=is) {
                        is.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        //加载
        private void doScanner(String packageName){

            URL url=this.getClass().getClassLoader().getResource("/"+packageName.replaceAll("\\.","/"));
            File classDir=new File(url.getFile());
            for(File file:classDir.listFiles()){
                if(file.isDirectory()){
                    doScanner(packageName+"."+file.getName());
                }else {
                    classNames.add(packageName+"."+file.getName().replace(".class",""));
                }
            }
        }

        //注册
        private void doRegistry(){
            if(classNames.isEmpty()){
                return;
            }
            try {
                for (String className:classNames){
                    Class clazz=Class.forName(className);
                    //spring中用多个子方法来处理
                    if(clazz.isAnnotationPresent(Controller.class)){
                        String beanName=toLowerFirstWord(clazz.getSimpleName());
                        //spring中在这个阶段不会直接put instance,这里put的是BeanDefinition
                        beanMap.put(beanName,clazz.newInstance());
                    }else if(clazz.isAnnotationPresent(Service.class)){
                        Service service= (Service) clazz.getAnnotation(Service.class);

                        //默认用类名首字母注入
                        //如果自己定义了beanName,那么优先使用自己定义的beanName
                        //如果是一个接口,使用接口的类型去自动注入
                        //spring中同样会分别调用不同的方法autowiredByName autowiredByType去实现

                        String serviceName=service.value();
                        if("".equals(serviceName.trim())){
                            serviceName=toLowerFirstWord(clazz.getSimpleName());
                        }
                        Object instance=clazz.newInstance();
                        beanMap.put(serviceName,instance);

                        Class<?>[] interfaces=clazz.getInterfaces();
                        for(Class<?> i:interfaces){
                            beanMap.put(i.getName(),instance);
                        }

                    }else {
                        continue;
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        //自动注入
        //在spring中需要调用getBean()方法来触发依赖注入
        private void doAutowired(){
            if(beanMap.isEmpty()){
                return;
            }
            for(Map.Entry<String,Object> entry:beanMap.entrySet()){
                Field[] fields=entry.getValue().getClass().getDeclaredFields();
                for (Field field:fields
                     ) {
                    if(!field.isAnnotationPresent(Autowired.class)){
                    return;
                    }
                    Autowired autowired=field.getAnnotation(Autowired.class);
                    //如果注释中包含自定义名字,则使用自定义名字;反之,使用默认的字段名
                    String beanName=autowired.value().trim();
                    if("".equals(beanName)){
                        beanName=field.getType().getName();
                    }
                    field.setAccessible(true);
                    try {
                        field.set(entry.getValue(),beanMap.get(beanName));
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }

            }
        }

        private void initHandlerMapping(){

        }
        private String toLowerFirstWord(String str){
        char[] charArr=str.toCharArray();
        charArr[0]+=32;
        return String.valueOf(charArr);
        }


}


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值