人生需要总结

手写MVC框架(三)-单独使用IOC示例

-------上一篇:手写MVC框架(二)-代码实现和使用示例------

背景

我在开发GMQ框架时使用了GMVC框架,使用过程中发现了一些不方便的地方,也都优化了。当前GMQ的传输基于http传输,我计划改为使用netty。因为我的代码是基于GMVC构建的,现在需求剥离掉web层,仅使用IOC功能。所以我就重新梳理了一下GMVC框架,最后发现是支持这样做的。

IOC使用示例

1、添加依赖

gmc项目:https://gitee.com/simpleha/gmvc.git

<dependency>
    <groupId>com.shuimutong</groupId>
    <artifactId>gmvc</artifactId>
    <version>1.0.2-SNAPSHOT</version>
</dependency>

2、编写业务代码

package com.shuimutong.gmvc_ioc_demo.service;

public interface TestService {
    void speak();
    String convertString(String s);
}

package com.shuimutong.gmvc_ioc_demo.service.impl;

import com.shuimutong.gmvc.annotation.XAutowired;
import com.shuimutong.gmvc.annotation.XService;
import com.shuimutong.gmvc_ioc_demo.bean.Person;
import com.shuimutong.gmvc_ioc_demo.dao.TestDao;
import com.shuimutong.gmvc_ioc_demo.service.TestService;

@XService
public class TestServiceImpl implements TestService {
    @XAutowired
    private TestDao testDao;
    
    @Override
    public void speak() {
        System.out.println("----TestServiceImpl-----speak--");
    }

    @Override
    public String convertString(String s) {
        Person p = testDao.findPerson();
        String perString = "addStr:" + s 
                + String.format(",Person(name:%s,age:%d)", p.getName(), p.getAge());
        return perString;
    }

}


package com.shuimutong.gmvc_ioc_demo.dao;

import com.shuimutong.gmvc_ioc_demo.bean.Person;

public interface TestDao {
    Person findPerson();
}


package com.shuimutong.gmvc_ioc_demo.dao.impl;

import com.shuimutong.gmvc.annotation.XRepository;
import com.shuimutong.gmvc_ioc_demo.bean.Person;
import com.shuimutong.gmvc_ioc_demo.dao.TestDao;

@XRepository
public class TestDaoImpl implements TestDao {

    @Override
    public Person findPerson() {
        return new Person();
    }

}

 

3、入口代码

public class App {
    public static void main( String[] args ) {
        Map<String, String> packageMap = new HashMap();
        //扫描包目录
        packageMap.put(GmvcSystemConst.BASE_PACKAGE, "com.shuimutong.gmvc_ioc_demo");
        try {
            InstanceManager.initAnnotationedResourcesAndDoInit(packageMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //获取类的实例
        TestService testService = (TestService) InstanceManager.getEntityByClazz(TestServiceImpl.class);
        String msg = testService.convertString("Hello,GMVC-IOC");
        System.out.println(msg);
    }
}

 

4、启动

addStr:Hello,GMVC-IOC,Person(name:name71,age:71)

IOC成功。

 

posted @ 2020-04-12 11:23  水木桶  阅读(341)  评论(0编辑  收藏  举报