实体类注入service并使用service
- 创建手动注入的处理器
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;
/**
* @Author felix fei
* @Date 2021/3/19 0019 10:30
* @Version 1.0.1
* @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> T getBean(String name) throws BeansException {
return (T) applicationContext.getBean(name);
}
public static <T> T getBean(Class<T> clz) throws BeansException {
return (T) applicationContext.getBean(clz);
}
}
- 创建service
package com.example.demo.service;
import com.example.demo.model.User;
import java.util.List;
import java.util.Map;
/**
* @Author felix fei
* @Date 2021/1/28 0028 14:58
* @Version 1.0.1
* @describe:
*/
public interface DemoService {
List<Map<String, Object>> listMap();
List<User> listEntity();
void add(User body);
List<Map<String, Object>> dmGetMethod();
}
- 创建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;
/**
* @Author felix fei
* @Date 2021/1/28 0028 14:58
* @Version 1.0.1
* @describe:
*/
@Service
public class DemoServiceImpl implements DemoService {
@Resource
private DemoMapper demoMapper;
@Override
public List<Map<String, Object>> listMap() {
return demoMapper.listMap();
}
@Override
public List<User> listEntity() {
return demoMapper.listEntity();
}
@Override
public void add(User body) {
demoMapper.insert(body);
}
@Override
public List<Map<String, Object>> dmGetMethod() {
return demoMapper.dmGetMethod();
}
}
- 在实体类中调用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;
/**
* @Author felix fei
* @Date 2021/3/4 0004 9:43
* @Version 1.0.1
* @describe:
*/
@Data
public class TestModel {
private String store;
private int storeage;
public void testUseService() {
// 进行service调用
DemoServiceImpl demoService = BeanContext.getApplicationContext()
.getBean(DemoServiceImpl.class);
List<User> users = demoService.listEntity();
System.out.println("获取到的数据=" + users.toString());
}
}
s
网友评论