-------Previous: Handwritten MVC framework (two) - code implementation and use examples------
background
I used the GMVC framework when developing the GMQ framework, and found some inconveniences in the process of using, which were also optimized. Currently, GMQ transmission is based on http transmission. I plan to use netty instead. Because my code is based on GMVC, now I need to peel off the web layer and only use IOC function. So I went through the GMVC framework again and found that it supports this.
IOC usage example
1. Add dependency
gmc project: https://gitee.com/simpleha/gmvc.git
<dependency>
<groupId>com.shuimutong</groupId>
<artifactId>gmvc</artifactId>
<version>1.0.2-SNAPSHOT</version>
</dependency>
2. Write business code
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. Entry code
public class App { public static void main( String[] args ) { Map<String, String> packageMap = new HashMap(); //Scan package directory packageMap.put(GmvcSystemConst.BASE_PACKAGE, "com.shuimutong.gmvc_ioc_demo"); try { InstanceManager.initAnnotationedResourcesAndDoInit(packageMap); } catch (Exception e) { e.printStackTrace(); } //Get an instance of a class TestService testService = (TestService) InstanceManager.getEntityByClazz(TestServiceImpl.class); String msg = testService.convertString("Hello,GMVC-IOC"); System.out.println(msg); } }
4. Start up
addStr:Hello,GMVC-IOC,Person(name:name71,age:71)
IOC is successful.