文章目录
1.目录 2.Resource.java 3.MonsterController.java 依赖注入Service调用方法 4.SunWebApplicationContext.java 1.executeResource方法完成依赖注入,先按照名字再按照类型 2.init方法调用
5.测试
1.目录
2.Resource.java
package com. sunxiansheng. springmvc. annotation ;
import java. lang. annotation. * ;
@Retention ( value = RetentionPolicy . RUNTIME )
@Target ( value = ElementType . FIELD )
@Documented
public @interface Resource {
String name ( ) default "" ;
}
3.MonsterController.java 依赖注入Service调用方法
package com. sunxiansheng. controller ;
import com. sunxiansheng. entity. Monster ;
import com. sunxiansheng. service. MonsterService ;
import com. sunxiansheng. springmvc. annotation. Controller ;
import com. sunxiansheng. springmvc. annotation. RequestMapping ;
import com. sunxiansheng. springmvc. annotation. Resource ;
import org. slf4j. Logger ;
import org. slf4j. LoggerFactory ;
import javax. servlet. http. HttpServletRequest ;
import javax. servlet. http. HttpServletResponse ;
import java. io. IOException ;
import java. io. PrintWriter ;
import java. util. List ;
@Controller
public class MonsterController {
@Resource
private MonsterService monsterService;
private static final Logger log = LoggerFactory . getLogger ( MonsterController . class ) ;
@RequestMapping ( url = "/list/monster" )
public void listMonster ( HttpServletRequest request, HttpServletResponse response) {
response. setContentType ( "text/html;charset=utf-8" ) ;
try {
PrintWriter writer = response. getWriter ( ) ;
List < Monster > monsters = monsterService. listMonster ( ) ;
for ( Monster monster : monsters) {
writer. println ( "id: " + monster. getId ( ) + ", name: " + monster. getName ( ) + ", skill: " + monster. getSkill ( ) + ", age: " + monster. getAge ( ) ) ;
}
log. info ( "查询怪物列表成功" ) ;
} catch ( IOException e) {
throw new RuntimeException ( e) ;
}
}
}
4.SunWebApplicationContext.java
1.executeResource方法完成依赖注入,先按照名字再按照类型
private void executeResource ( ) {
if ( ioc. isEmpty ( ) ) {
return ;
}
ioc. forEach ( ( key, value) -> {
try {
Class < ? > clazz = value. getClass ( ) ;
Field [ ] fields = clazz. getDeclaredFields ( ) ;
for ( Field field : fields) {
if ( field. isAnnotationPresent ( Resource . class ) ) {
Resource resource = field. getAnnotation ( Resource . class ) ;
String name = resource. name ( ) ;
Object o = ioc. get ( name) ;
if ( Objects . isNull ( o) ) {
Class < ? > type = field. getType ( ) ;
String keyName = toLowerFirstWord ( type. getSimpleName ( ) ) ;
o = ioc. get ( keyName) ;
}
field. setAccessible ( true ) ;
field. set ( value, o) ;
if ( Objects . nonNull ( o) ) {
log. info ( "依赖注入成功,属性名:{},属性值:{}" , field. getName ( ) , o) ;
}
}
}
} catch ( Exception e) {
e. printStackTrace ( ) ;
}
} ) ;
}
2.init方法调用
5.测试