# Spring实体类注入service并使用service **Repository Path**: fpfgitmy_admin/spring-injection-service ## Basic Information - **Project Name**: Spring实体类注入service并使用service - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 0 - **Created**: 2021-04-28 - **Last Updated**: 2021-04-28 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README #### 实体类注入service并使用service 1. 创建手动注入的处理器 2. ``` package com.felixfei.demo.config; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; /** * @describe: 手动注入类的处理器 */ @Component public class BeanContext implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { BeanContext.applicationContext = applicationContext; } public static ApplicationContext getApplicationContext() { return applicationContext; } @SuppressWarnings("unchecked") public static T getBean(String name) throws BeansException { return (T) applicationContext.getBean(name); } public static T getBean(Class clz) throws BeansException { return (T) applicationContext.getBean(clz); } } ``` 2. 创建service ``` package com.example.demo.service; import com.example.demo.model.User; import java.util.List; import java.util.Map; /** * @describe: */ public interface DemoService { List> listMap(); List listEntity(); void add(User body); List> dmGetMethod(); } ``` 3. 创建serviceImpl ``` package com.example.demo.service.impl; import com.example.demo.mapper.DemoMapper; import com.example.demo.model.User; import com.example.demo.service.DemoService; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; import javax.annotation.Resource; /** * @describe: */ @Service public class DemoServiceImpl implements DemoService { @Resource private DemoMapper demoMapper; @Override public List> listMap() { return demoMapper.listMap(); } @Override public List listEntity() { return demoMapper.listEntity(); } @Override public void add(User body) { demoMapper.insert(body); } @Override public List> dmGetMethod() { return demoMapper.dmGetMethod(); } } ``` 4. 在实体类中调用service服务 ``` package com.example.demo.model; import com.example.demo.config.BeanContext; import com.example.demo.service.impl.DemoServiceImpl; import lombok.Data; import java.util.List; /** * @describe: */ @Data public class TestModel { private String store; private int storeage; public void testUseService() { // 进行service调用 DemoServiceImpl demoService = BeanContext.getApplicationContext() .getBean(DemoServiceImpl.class); List users = demoService.listEntity(); System.out.println("获取到的数据=" + users.toString()); } } s ```