如何在main方法是 使用SpringBoot中的service. 查询数据库。 main方法
package java456.com.utils; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component public class SpringUtil implements ApplicationContextAware { private static ApplicationContext applicationContext = null; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { if(SpringUtil.applicationContext == null){ SpringUtil.applicationContext = applicationContext; } } //获取applicationContext public static ApplicationContext getApplicationContext() { return applicationContext; } //通过name获取 Bean. public static Object getBean(String name){ return getApplicationContext().getBean(name); } //通过class获取Bean. public static <T> T getBean(Class<T> clazz){ return getApplicationContext().getBean(clazz); } //通过name,以及Clazz返回指定的Bean public static <T> T getBean(String name,Class<T> clazz){ return getApplicationContext().getBean(name, clazz); } }
package java456.com.utils; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import java456.com.entity.Job; import java456.com.mapper.JobMapper; import java456.com.service.JobService; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.stereotype.Component; import org.springframework.stereotype.Controller; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.CrossOrigin; import javax.annotation.PostConstruct; import java.util.HashMap; import java.util.Map; @SpringBootApplication @MapperScan(basePackages = {"java456.com.service"}) @MapperScan(basePackages = {"java456.com.mapper"}) public class SpringTest { @Autowired private static JobService jobService; public static void main(String [] args){ SpringApplication.run(SpringTest.class, args); ApplicationContext context = SpringUtil.getApplicationContext(); JobMapper mapper = context.getBean(JobMapper.class);// 注意是Service,不是ServiceImpl System.out.println(mapper); LambdaQueryWrapper<Job> queryWrapper = new LambdaQueryWrapper<>(); queryWrapper.eq(Job::getId, 368); Job job = mapper.selectOne(queryWrapper); } }
站长微信:xiaomao0055
站长QQ:14496453