springboot项目用junit进行单元测试,无法注入bean

这个是报错信息:
图片说明
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'cn.com.zhshzh.xs.pms.XsApplicationTests': Unsatisfied dependency expressed through field 'reimbursementInfoProcService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'cn.com.zhshzh.xs.pms.system.test.service.ReimbursementInfoProcService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:587)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:373)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1344)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:400)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:44)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:242)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'cn.com.zhshzh.xs.pms.system.test.service.ReimbursementInfoProcService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1509)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1065)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:584)
... 29 common frames omitted

这个是测试类代码:

package cn.com.zhshzh.xs.pms;

import java.math.BigDecimal;
import java.util.Date;

import javax.ws.rs.core.Application;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import cn.com.zhshzh.xs.pms.system.test.PO.ReimbursementInfoProc;
import cn.com.zhshzh.xs.pms.system.test.service.ReimbursementInfoProcService;
import lombok.extern.slf4j.Slf4j;

// 获取启动类,加载配置,确定装载 Spring 程序的装载方法,它回去寻找 主配置启动类(被 @SpringBootApplication 注解的)
@SpringBootTest(classes = Application.class)
// 让 JUnit 运行 Spring 的测试环境, 获得 Spring 环境的上下文的支持
@RunWith(SpringRunner.class)
@WebAppConfiguration
@Slf4j
public class XsApplicationTests {
@Autowired
private ReimbursementInfoProcService reimbursementInfoProcService;

@Test
public void TestCase() {
    ReimbursementInfoProc reimbursementInfoProc = new ReimbursementInfoProc();
    reimbursementInfoProc.setProcessId("1");
    reimbursementInfoProc.setPostId("1");
    reimbursementInfoProc.setReimbursementPerson("23456");
    reimbursementInfoProc.setReimbursementMoney(new BigDecimal("50.00"));
    reimbursementInfoProc.setReimbursementDate(new Date());
    reimbursementInfoProc.setApprovalOpinion("审批通过");
    reimbursementInfoProc.setCreateBy("23456");
    reimbursementInfoProc.setUpdateBy("23456");
    try {
        reimbursementInfoProcService.insertReimbursementInfo(reimbursementInfoProc);
    } catch (Exception e) {
        log.error("message", e);
    }
}

}

3个回答

首先把SpringBootTest注解中的Application.class改为XsApplication.class(项目的启动类是XsApplication),再加上webEnvironment=SpringBootTest.WebEnvironment.RANDOM_PORT,最后再把@WebAppConfiguration注解删了就行了

注入的bean是否上下文有扫描到,是否实现依赖引入

ReimbursementInfoProcServiceImpl类上加@Service

ko289830707
Solo丶慕颜 设置成SpringJUnit4ClassRunner.class
大约一年之前 回复
ko289830707
Solo丶慕颜 Runwith注解中value
大约一年之前 回复
king_bt
瘦小王 有注解的,不是这个问题
大约一年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
springboot 多模块项目进行service层的单元测试时,mapper接口无法注入进来

如题。service中注入mapper接口都可以正常获取数据。在写service的单元测试时无法注入mapper接口。 service测试类如下: ``` @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = TestRunner.class) public class LoginServiceTest { @Autowired private UserMapper userMapper; @Test public void isLogin() throws Exception { User user = new User(); user.setUserName("wangjing"); user.setPassword("1234"); Assert.assertEquals(1,userMapper.isLogin(user)); } } ``` mapper接口如下: ``` @Mapper @Component(value = "userMapper") public interface UserMapper { int isLogin(User user); } ``` 报错信息如下: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.pinganfu.dayu.service.LoginServiceTest': Unsatisfied dependency expressed through field 'userMapper'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.pinganfu.dayu.dal.mapper.UserMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:386) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83) at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:44) at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191) at org.junit.runners.Suite.runChild(Suite.java:128) at org.junit.runners.Suite.runChild(Suite.java:27) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68) at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47) at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242) at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70) Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.pinganfu.dayu.dal.mapper.UserMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1486) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585) ... 36 more

SpringBoot Junit测试问题

请教下大神: 在普通代码中加上注解后可以直接完成对象注入 在test包下建立专门的测试类时,对象无法直接注入,需在注解后配置 但是加上配置集成的mybatis的mapper文件也无法完成注入。

springboot+dubbo在写单元测试的时候controller中的@Reference注解属性为null

问题描述 项目中运用springboot+dubbo注解方式的配置开发,正常启动项目没有什么问题,但是当我在写单元测试的时候,发现@Reference标注的属性为null,导致调用空指针异常. 相关代码 待测试方法: ``` @RestController @RequestMapping("/api/user") public class UserController { @Reference(version = "${dubbo.service.version}") private IUserService userService; @PostMapping(value="/login", produces="application/json;charset=UTF-8") public JsonApi login(String username, String password) { User search = new User(); search.setUsername(username); User user = userService.selectUserBy(search); if (StringUtils.isEmpty(user)){ search.setUsername(null); search.setEmail(username); user = userService.selectUserBy(search); } if (StringUtils.isEmpty(user)){ throw new AuthorizeException(ErrorCode.USER_UNKNOWN_ACCOUNT); } return JsonApi.isOk()..data(user); } } ``` 测试方法: ``` @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @SpringBootTest public class UserControllerTest { private MockMvc mvc; @Before public void setUp() { mvc = MockMvcBuilders.standaloneSetup(new UserController()).build(); } @Test public void login() throws Exception { RequestBuilder request = post("/api/user/login") .contentType(MediaType.APPLICATION_JSON) .param("username","test") .param("password","123456"); String rs = mvc.perform(request) //.andDo(print()) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(rs); } } ``` 在运行测试用例的时候,发现private IUserService userService为空 ![图片说明](https://img-ask.csdn.net/upload/201809/26/1537953108_564995.png) 网上都是说和springMvc集成的时候加载顺序会导致这个空指针异常,但是我的项目正常启动是可以访问的,就是在测试用例的时候回出现空,不知道什么原因. 是哪里的配置没有配置对吗?

多个模块项目使用maven依赖,在做Junit单元测试时,其他模块的类不能注入

如题: 我们当前通过maven依赖,依赖了多个模块,在做junit单元测试时我们的单元测试类中 引入了其他模块声明的服务类或者是Dao类,通过@Autowired注入,spring无法对该类注入 请大神解答一下

关于Junit结合spring测试加载bean的问题

问题一: public class text { private static final Logger logger = LoggerFactory.getLogger(text.class); @Autowired private NumBasicJob numBasicJob; @Test public void insert() { ApplicationContext act=new ClassPathXmlApplicationContext("spring.xml"); NumBasicJob p=(NumBasicJob) act.getBean("numBasicJob"); p.ExecuteOcfJob(text.class); //numBasicJob.ExecuteOcfJob(text.class); } } 我代码全部使用注解,加载spring并没有报错,但是获取不到bean,也就是p为空,我认为可能是 ApplicationContext act=new ClassPathXmlApplicationContext("spring.xml ");不支持注解,不知道对不对? 问题2: public class text extends BaseJunit4Test { private static final Logger logger = LoggerFactory.getLogger(text.class); @Autowired private NumBasicJob numBasicJob; @Test public void insert() { /* ApplicationContext act=new ClassPathXmlApplicationContext("spring.xml"); NumBasicJob p=(NumBasicJob) act.getBean("numBasicJob"); p.ExecuteOcfJob(text.class);*/ numBasicJob.ExecuteOcfJob(text.class); } } @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({ "classpath:spring.xml" }) public class BaseJunit4Test { private static final Logger LOG_RECORD=Logger.getLogger(OcfProductBasicJob.class); @Before public void init() { //在运行测试之前的业务代码 LOG_RECORD.info("start to execute task," + new Date().toString()); } @After public void after() { //在测试完成之后的业务代码 LOG_RECORD.info("end to execute task," + new Date().toString()); } } 按道理说,我使用junit结合spring进行测试的时候,numBasicJob不应该为空,因为这个支持注解。

JUnit Spring 测试报 NoSuchBeanDefinitionException

在tomcat下是正常的,但是用JUnit测试就报错: ``` Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.servlet.ServletContext] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.annotation.Resource(shareable=true, mappedName=, type=class java.lang.Object, authenticationType=CONTAINER, lookup=, description=, name=)} ```

如何@autowired注入一个带有final属性的bean

@Service public class Demo1Impl { private final String name; Demo1Impl(String name) { this.name = name; } public String getName(int i) { return "name"; } } 单元测试要测试这个getName方法 @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = DemoApplication.class) class Demo1ImplTest { @Autowired Demo1Impl demo1; @Test void getName() { System.out.println(demo1.getName(1)); } } run后报错,显示找不到合格的bean,这是一个Springboot项目,单元测试的时候我该如何注入Demo1Impl呢?

Springboot,使用@Autowired疑似注入失败,报空指针错误

项目结构: ![图片说明](https://img-ask.csdn.net/upload/202005/07/1588846375_795799.png) User类: ``` package com.test.mp.mp1111.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import lombok.Data; import org.springframework.stereotype.Component; @Data public class User { // @TableId(type = IdType.AUTO) private Long id; private Integer age; private String name; private String email; } ``` UserMapper: ``` package com.test.mp.mp1111.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.test.mp.mp1111.entity.User; import lombok.Data; import org.apache.ibatis.annotations.Mapper; import org.springframework.context.annotation.ComponentScan; import org.springframework.stereotype.Component; import org.springframework.stereotype.Repository; @Component public interface UserMapper extends BaseMapper<User> { } ``` Mp1111ApplicationTests: ``` package com.test.mp.mp1111; import com.test.mp.mp1111.entity.User; import com.test.mp.mp1111.mapper.UserMapper; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.List; @SpringBootTest class Mp1111ApplicationTests { @Autowired private UserMapper userMapper; @Test public void testUpdateById() { if (userMapper == null) { System.out.println("空指针"); } } } ``` 项目pom.xml ``` <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.7.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.test.mp</groupId> <artifactId>mp1111</artifactId> <version>0.0.1-SNAPSHOT</version> <name>mp1111</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!--mybatis-plus--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.0.5</version> </dependency> <!--mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!--lombok用来简化实体类--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter</artifactId> <version>RELEASE</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> ``` 我运行Mp1111ApplicationTests中的testUpdateById方法, 显示userMapper为空指针,这是为什么呀

spring-test junit4出现Could not autowire field问题

不知道为什么自动注入失败?帮忙看看什么原因?拜谢~~ 1. spring配置文件 <!-- 加载配置属性文件 --> <context:property-placeholder ignore-unresolvable="true" location="classpath:config.properties" /> <!-- 自动扫描(自动注入) --> <context:component-scan base-package="com.epuxun.eshuixiang"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <!-- 引入其他配置文件 --> <import resource="classpath:spring-context-ehcache.xml" /> <import resource="classpath:spring-context-mybatis.xml" /> <import resource="classpath:spring-context-captcha.xml" /> <import resource="classpath:spring-context-jedis.xml" /> <import resource="classpath:spring-context-task.xml" /> 2.@service 注入(这里不贴出所有代码了,太长,主要看@service) @Service("accountService") @Transactional(readOnly = true) public class AccountServiceImpl implements IAccountService { private Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); private Logger logger = Logger.getLogger(getClass()); @Autowired private AccountMapper accountMapper; 3.测试类使用spring-test+junit4 @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:spring-context*.xml"}) public class TestMyDm{ private static final Logger logger = Logger.getLogger(TestMyDm.class); @Autowired private IAccountService accountService; @Test public void test1() { Account account = accountService.findByMemberId("ba175fbea5684e809e46d46ca886e18a"); logger.info(JSON.toJSON(account)); } } 4.报错代码 [org.springframework.context.support.GenericApplicationContext]Refreshing org.springframework.context.support.GenericApplicationContext@65fbadc2: startup date [Thu Jan 14 16:03:58 CST 2016]; root of context hierarchy [org.springframework.test.context.TestContextManager]Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@25a57416] to prepare test instance [com.epuxun.eshuixiang.TestMyDm@116863a9] org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.epuxun.eshuixiang.TestMyDm': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.epuxun.eshuixiang.modules.account.service.IAccountService com.epuxun.eshuixiang.TestMyDm.accountService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.epuxun.eshuixiang.modules.account.service.IAccountService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:301) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1186) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:384) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:110) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75) at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:331) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:213) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:290) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:292) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:233) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:87) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71) at org.junit.runners.ParentRunner.run(ParentRunner.java:309) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:176) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.epuxun.eshuixiang.modules.account.service.IAccountService com.epuxun.eshuixiang.TestMyDm.accountService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.epuxun.eshuixiang.modules.account.service.IAccountService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:522) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:298) ... 26 more Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.epuxun.eshuixiang.modules.account.service.IAccountService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1118) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:967) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:862) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:494) ... 28 more [org.springframework.context.support.GenericApplicationContext]Closing org.springframework.context.support.GenericApplicationContext@65fbadc2: startup date [Thu Jan 14 16:03:58 CST 2016]; root of context hierarchy

spring使用JUnit时autowired报错,controller里面autowired可以的

试了好多办法还是不行,不知道哪里配错了。。麻烦大神帮看一下 异常信息: ``` SEVERE: Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@5f98de7] to prepare test instance [com.xxx.xxx.entity.UserTest@42d33bc1] org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.xxx.xxx.entity.UserTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.xxx.xxx.service.UserService com.xxx.xxx.entity.UserTest.service; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.xxx.xxx.service.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:374) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:110) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75) at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:321) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:220) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:301) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:303) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:240) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.xxx.xxx.service.UserService com.xxx.xxx.entity.UserTest.service; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.xxx.xxx.service.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:502) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:282) ... 26 more Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.xxx.xxx.service.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:920) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:789) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:703) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:474) ... 28 more ``` UserTest.java ``` package com.xxx.xxx.entity; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.xxx.xxx.service.UserService; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"classpath*:**/applicationContext.xml","classpath*:**/springmvc-servlet.xml"}) public class UserTest { @Autowired UserService service; //@Ignore @Test public void userHPTest() { System.out.println(service.get("889e4d63ff024b29a173ab52ce174cc9")); } } ``` UserServiceImpl.java(这个是service的实现) ``` package com.xxx.xxx.serviceimpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.xxx.xxx.dao.BaseDao; import com.xxx.xxx.dao.UserDao; import com.xxx.xxx.entity.User; import com.xxx.xxx.service.UserService; @Service("userServiceImpl") public class UserServiceImpl extends BaseServiceImpl<User> implements UserService { @Autowired UserDao dao; @Override protected BaseDao<User> getDao() { return dao; } } ``` applicationContext.xml(我感觉我可能是这里不对) ``` <?xml version="1.0" encoding="UTF-8" ?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation=" http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"> <context:component-scan base-package="com.xxx.xxx.dao"></context:component-scan> <context:component-scan base-package="com.xxx.xxx.daoimpl"></context:component-scan> <context:component-scan base-package="com.xxx.xxx.service"></context:component-scan> <context:component-scan base-package="com.xxx.xxx.serviceimpl"></context:component-scan> </beans> ``` springmvc-servlet.xml(我在controller里autowired是没有问题的) ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <context:component-scan base-package="com.xxx.xxx.controller"></context:component-scan> <context:component-scan base-package="com.xxx.xxx.dao"></context:component-scan> <context:component-scan base-package="com.xxx.xxx.daoimpl"></context:component-scan> <context:component-scan base-package="com.xxx.xxx.service"></context:component-scan> <context:component-scan base-package="com.xxx.xxx.serviceimpl"></context:component-scan> <mvc:annotation-driven/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans> ```

junit测试@mock的thenReturn始终返回0

小弟刚接触junit,今天写了个mock,如下 @Mock private XXXDao xxxDao; @InjectMocks private XXXService xxxService @Test (其它内容略) when(xxxDao.test(params)).thenReturn(1); Integer reNum = xxxService.doing();//service里有xxxDao.test方法,但返回值一直是0 求各位帮帮忙,看看是什么问题?感谢!

spring整合mybatis 注入出错 求助各位大神

![目录结构](https://img-ask.csdn.net/upload/201704/13/1492074562_72832.png) 报错 org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cn.jscoin.UserTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private cn.jscoin.jslj.mapper.UserMapper cn.jscoin.UserTest.userMapper; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [cn.jscoin.jslj.mapper.UserMapper] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1202) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:385) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83) at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:212) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:200) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:252) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:254) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:217) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private cn.jscoin.jslj.mapper.UserMapper cn.jscoin.UserTest.userMapper; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [cn.jscoin.jslj.mapper.UserMapper] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:558) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331) ... 26 more Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [cn.jscoin.jslj.mapper.UserMapper] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1308) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1054) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:949) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:530) ... 28 more 测试代码 ``` @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations="classpath*:applicationContext.xml") public class UserTest { @Autowired private UserMapper userMapper; @Test public void testAdd(){ User user = new User(); user.setAge(123); userMapper.add(user); } } ``` ![配置文件位置](https://img-ask.csdn.net/upload/201704/13/1492074774_341390.png) applicationContext.xml <!-- 扫描包 --> <context:component-scan base-package="cn.jscoin" /> <!-- 数据源 druid --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${driverClassName}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> </bean> <!-- 读取Property --> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <set> <value>classpath:jdbc.properties</value> </set> </property> </bean> <!-- Mybatis工厂 --> <bean class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 数据源 --> <property name="dataSource" ref="dataSource" /> <!-- 配置Mybati的核心配置文件 --> <property name="configLocation" value="classpath:mybatis-config.xml" /> </bean> <!-- 扫描基本包 Mapper 接口 Mapper文件 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="cn.jscoin.jslj.mapper" /> </bean> <!-- 事务 @Transactional --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 开启注解的事务 --> <tx:annotation-driven transaction-manager="transactionManager" />

Spring报错:expected at least 1 matching bean还是没解决

严重: Exception sending context initialized event to listener instance of class cn.tg.core.web.ApplicationListener org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'systemConfigMngImpl': Autowiring of methods failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void cn.tg.core.manager.impl.SystemConfigMngImpl.setDao(cn.tg.core.dao.SystemConfigDao); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [cn.tg.core.dao.SystemConfigDao] is defined: Unsatisfied dependency of type [interface cn.tg.core.dao.SystemConfigDao]: expected at least 1 matching bean 实体类 SystemConfig Java代码 @Entity @Table(name = "tg_system") public class SystemConfig implements Serializable { private static final long serialVersionUID = 2776461377886734127L; private long id; @Id @GeneratedValue(strategy = GenerationType.AUTO) public long getId() { return id; } …… @Entity @Table(name = "tg_system") public class SystemConfig implements Serializable { private static final long serialVersionUID = 2776461377886734127L; private long id; @Id @GeneratedValue(strategy = GenerationType.AUTO) public long getId() { return id; } …… Mng接口 Java代码 1.public interface SystemConfigMng extends TGCoreManager<SystemConfig>{ 2.} public interface SystemConfigMng extends TGCoreManager<SystemConfig>{ } Mng实现类 @Service // systemConfigMngImpl @Transactional public class SystemConfigMngImpl extends TGCoreManagerImpl<SystemConfig> implements SystemConfigMng { @Autowired public void setDao(SystemConfigDao dao) { super.setDao(dao); } public SystemConfigDao getDao() { return (SystemConfigDao) super.getDao(); } } 在一个servelt里: Java代码 1.public final class ApplicationListener implements ServletContextListener { 2. private static final String BEAN_NAME = "systemConfigMngImpl"; 3. private static final Logger log = LoggerFactory 4. .getLogger(ApplicationListener.class); 5. 6. public void contextDestroyed(ServletContextEvent event) { 7. } 8. 9. public void contextInitialized(ServletContextEvent event) { 10. WebApplicationContext wac = WebApplicationContextUtils 11. .getRequiredWebApplicationContext(event.getServletContext()); 12. systemConfigMng = (SystemConfigMng) wac.getBean(BEAN_NAME, SystemConfigMng.class); 13. log.info("系统启动,读取所有站点信息到缓存。"); 14. systemConfigMng.loadAllSystemConfigToCache(); 15. } 16. 17. private SystemConfigMng systemConfigMng; 18.} public final class ApplicationListener implements ServletContextListener { private static final String BEAN_NAME = "systemConfigMngImpl"; private static final Logger log = LoggerFactory .getLogger(ApplicationListener.class); public void contextDestroyed(ServletContextEvent event) { } public void contextInitialized(ServletContextEvent event) { WebApplicationContext wac = WebApplicationContextUtils .getRequiredWebApplicationContext(event.getServletContext()); systemConfigMng = (SystemConfigMng) wac.getBean(BEAN_NAME, SystemConfigMng.class); log.info("系统启动,读取所有站点信息到缓存。"); systemConfigMng.loadAllSystemConfigToCache(); } private SystemConfigMng systemConfigMng; } 用了systemConfigMngImpl就报上面的错,那位大侠能帮忙解决吗?现在那个热锅上的蚂蚁啊!!只有那么多分了……万分感谢!!! Java代码 1.public interface BaseDao<T extends Serializable> {…//底层dao接口…} 2. 3.@Repository 4.public abstract class BaseDaoImpl<T extends Serializable> implements BaseDao<T> { 5. protected Logger log = LoggerFactory.getLogger(getClass()); 6. 7. protected SessionFactory sessionFactory; 8. 9. @Autowired 10. public void setSessionFactory(SessionFactory sessionFactory) { 11. this.sessionFactory = sessionFactory; 12. } 13.…//底层dao实现类… 14.} 15.public interface BaseManager<T extends Serializable> {//底层 16.Mng接口} 17. 18.@Transactional 19.public class BaseManagerImpl<T extends Serializable> implements BaseManager<T> { 20. protected Logger log = LoggerFactory.getLogger(getClass()); 21. private BaseDao<T> dao; 22. 23. public void setDao(BaseDao<T> dao) { 24. this.dao = dao; 25. } 26. 27. protected BaseDao<T> getDao() { 28. return this.dao; 29. } 30.//底层Mng实现类 31.} 32. 33.public interface TGCoreDao<T extends Serializable> extends BaseDao<T> { 34. 35.} 36. 37.public class TGCoreDaoImpl<T extends Serializable> extends BaseDaoImpl<T> 38. implements TGCoreDao<T> { 39. 40. 41.} 42. 43.public interface TGCoreManager<T extends Serializable> extends BaseManager<T> { 44.} 45. 46.public class TGCoreManagerImpl<T extends Serializable> extends 47. BaseManagerImpl<T> implements TGCoreManager<T> { 48.} public interface BaseDao<T extends Serializable> {…//底层dao接口…} @Repository public abstract class BaseDaoImpl<T extends Serializable> implements BaseDao<T> { protected Logger log = LoggerFactory.getLogger(getClass()); protected SessionFactory sessionFactory; @Autowired public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } …//底层dao实现类… } public interface BaseManager<T extends Serializable> {//底层 Mng接口} @Transactional public class BaseManagerImpl<T extends Serializable> implements BaseManager<T> { protected Logger log = LoggerFactory.getLogger(getClass()); private BaseDao<T> dao; public void setDao(BaseDao<T> dao) { this.dao = dao; } protected BaseDao<T> getDao() { return this.dao; } //底层Mng实现类 } public interface TGCoreDao<T extends Serializable> extends BaseDao<T> { } public class TGCoreDaoImpl<T extends Serializable> extends BaseDaoImpl<T> implements TGCoreDao<T> { } public interface TGCoreManager<T extends Serializable> extends BaseManager<T> { } public class TGCoreManagerImpl<T extends Serializable> extends BaseManagerImpl<T> implements TGCoreManager<T> { } Dao接口 Java代码 1.public interface SystemConfigDao extends TGCoreDao<SystemConfig> { 2. 3.} public interface SystemConfigDao extends TGCoreDao<SystemConfig> { } Dao实现类 Java代码 1.public class SystemConfigDaoImpl extends TGCoreDaoImpl<SystemConfig> implements SystemConfigDao{ 2. 3.}

求助:springboot中接口和实现类不在同一个jar中,@Autowired失败

# 1.demo ## 1-1.接口定义 包名:com.example.demo 接口:ITest ``` package com.example.demo; public interface ITest { void find(); } ``` ## 1.2.接口使用 ``` @Autowired @Qualifier("myTest2") // ←自动注入不同的实现类 private ITest itest; // 调用实现类的方法 itest.find(); ``` ## 1.3.同一jar中定义实现类 ``` package com.example.demo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @Component public class MyTest2 implements ITest { private static final Logger LOGGER = LoggerFactory.getLogger(MyTest2.class); @Override public void find() { LOGGER.info("MyTest2#find"); } } ``` # 2.demo01 在其他jar中定义实现类【**包名相同**】 ``` package com.example.demo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @Component public class MyTest implements ITest { private static final Logger LOGGER = LoggerFactory.getLogger(MyTest.class); @Override public void find() { LOGGER.info("MyTest#find"); } } ``` **注)Springboot入口类:** ``` @SpringBootApplication(scanBasePackages = { "com.example" }) public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } ``` 然后修改上面【1.2.接口使用】中@Qualifier的实现类,运行后发现: 1.@Qualifier("myTest") -------> 运行失败,错误如下: > *************************** > APPLICATION FAILED TO START > *************************** > > Description: > > Field itest in com.example.demo.MyRunner required a bean of type 'com.example.demo.ITest' that could not be found. > > > Action: > > Consider defining a bean of type 'com.example.demo.ITest' in your configuration. 2.@Qualifier("myTest2") -------> 运行成功

@Autowired注入为null,空指针异常。

Spring mvc + hibernate 的框架中,在非Controller下使用@Autowired注入失败,空指针异常。 配置文件中已经加入了如下的内容 <context:component-scan base-package="com.cnwaterinfo.csp.*"/> <!-- 使用annotation 自动注册bean,并保证@Required,@Autowired的属性被注入 --> <context:component-scan base-package="com.cnwaterinfo.csp."> <context:exclude-filter type="regex" expression=".*.*Controller$" /> </context:component-scan> Service类: @Service("realtimeDataService") @Transactional public class RealtimeDataServiceImpl implements RealtimeDataService { @Autowired private RealtimeDataDao rdd; .... 在非Controller下 public class NetWorkPascalRealtimeDataHandler { private final static Logger log = Logger .getLogger(NetWorkPascalRealtimeDataHandler.class); @Autowired private RealtimeDataService realtimeDataService; ..... 此时realtimeDataService为NULL,调用任何方法都会空指针异常 何解?

spring 注入 dao,引用的时候为null

![图片说明](https://img-ask.csdn.net/upload/201605/14/1463160241_79433.png) spring配置文件如下: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <!--<import resource="ApplicationContext-Bdxm.xml" /> In ApplicationContext.xml--> <beans default-lazy-init="false" default-dependency-check="none" default-autowire="no"> <bean id="IBdxmService" parent="baseTransactionProxy"> <property name="target"> <bean class="cn.com.ebidding.web.dljk.bdxm.service.impl.BdxmService"> <property name="dao" ref="IBdxmDao" /> </bean> </property> </bean> <bean id="IBdxmAuth" parent="baseTransactionProxy"> <property name="target"> <bean class="cn.com.ebidding.web.dljk.bdxm.auth.impl.BdxmAuth" singleton="false"> <property name="dao" ref="IBdxmDao" /> </bean> </property> </bean> <bean id="IBdxmBusiness" parent="baseTransactionProxy"> <property name="target"> <bean class="cn.com.ebidding.web.dljk.bdxm.business.impl.BdxmBusiness"> <property name="dao" ref="IBdxmDao" /> </bean> </property> </bean> <bean id="IBdxmValidate" parent="baseTransactionProxy"> <property name="target"> <bean class="cn.com.ebidding.web.dljk.bdxm.validate.impl.BdxmValidate"> <property name="dao" ref="IBdxmDao" /> </bean> </property> </bean> <bean id="IBdxmDao" class="cn.com.ebidding.web.dljk.bdxm.dao.impl.BdxmDao"> <property name="sessionFactory" ref="sessionFactory" /> </bean> </beans>

spring整合hibernate时,报错说找不到bean,求大神帮忙

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDao': Unsatisfied dependency expressed through method 'setSessionFactory' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactoty' defined in class path resource [spring-hibernate.xml]: Invocation of init method failed; nested exception is org.hibernate.MappingException: invalid configuration at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:667) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139) at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:93) at sy.test.TestHibernate.test(TestHibernate.java:21) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactoty' defined in class path resource [spring-hibernate.xml]: Invocation of init method failed; nested exception is org.hibernate.MappingException: invalid configuration at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:659) ... 38 more Caused by: org.hibernate.MappingException: invalid configuration at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2160) at org.hibernate.cfg.Configuration.configure(Configuration.java:2113) at org.springframework.orm.hibernate4.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:348) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ... 48 more Caused by: org.xml.sax.SAXParseException; lineNumber: 2; columnNumber: 7; 文档无效: 找不到语法。 at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:203) at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:134) at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:396) at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:327) at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:284) at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:229) at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(XMLNSDocumentScannerImpl.java:614) at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:3135) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:880) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:606) at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:118) at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:510) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:848) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:777) at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141) at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1213) at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:643) at org.dom4j.io.SAXReader.read(SAXReader.java:465) at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2157) ... 52 more

springboot+mybatis-plus中启动程序报以下错误,请问是pom文件不对吗?

Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'adminController': Unsatisfied dependency expressed through field 'doctorService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'doctorServiceImpl': Unsatisfied dependency expressed through field 'baseMapper'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'doctorMapper' defined in file [F:\Intellij\Project\appointment\target\classes\com\example\appointment\modular\doctor\dao\DoctorMapper.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [com/baomidou/mybatisplus/autoconfigure/MybatisPlusAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.ibatis.session.SqlSessionFactory]: Factory method 'sqlSessionFactory' threw exception; nested exception is org.springframework.core.NestedIOException: Failed to parse mapping resource: 'file [F:\Intellij\Project\appointment\target\classes\com\example\appointment\modular\admin\dao\mapper\AdminMapper.xml]'; nested exception is org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. The XML location is 'file [F:\Intellij\Project\appointment\target\classes\com\example\appointment\modular\admin\dao\mapper\AdminMapper.xml]'. Cause: org.apache.ibatis.builder.BuilderException: Error resolving class. Cause: org.apache.ibatis.type.TypeException: Could not resolve type alias 'com.example.demo.modular.admin.entity.Admin'. Cause: java.lang.ClassNotFoundException: Cannot find class: com.example.demo.modular.admin.entity.Admin

spring注入jdbcTemplate时一直为空指针,求大牛指导

已经在spring配置文件中配置了jdbcTemplate的bean,但是在测试类中jdbcTemlpate的注入报空指针 ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd "> <!-- 配置spring的jdbcTemplate--> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 设置spring扫包路径 --> <context:component-scan base-package="com.hzbckj.spring" /> <!-- 导入资源文件 --> <context:property-placeholder location="db.properties" /> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="${user}"></property> <property name="password" value="${password}"></property> <property name="jdbcUrl" value="${jdbcUrl}"></property> <property name="driverClass" value="${driverClass}"></property> </bean> </beans> ``` 这是spring配置文件 ``` package com.hzbckj.spring.test; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component; import javax.annotation.Resource; /** * Created by jackson on 2017/2/6. */ @Component public class dataSourceTest { @Resource(name = "jdbcTemplate") private JdbcTemplate jdbcTemplate; public JdbcTemplate getJdbcTemplate() { return jdbcTemplate; } public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @Test public void testJdbc(){ // ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); // JdbcTemplate jdbcTemplate = (JdbcTemplate)ctx.getBean("jdbcTemplate"); String sql = "INSERT INTO user(name, balance) values('Jonn', 200)"; jdbcTemplate.execute(sql); } } ``` 这是使用的地方 执行时jdbcTemplate一直报空

大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了

大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

Java基础知识面试题(2020最新版)

文章目录Java概述何为编程什么是Javajdk1.5之后的三大版本JVM、JRE和JDK的关系什么是跨平台性?原理是什么Java语言有哪些特点什么是字节码?采用字节码的最大好处是什么什么是Java程序的主类?应用程序和小程序的主类有何不同?Java应用程序与小程序之间有那些差别?Java和C++的区别Oracle JDK 和 OpenJDK 的对比基础语法数据类型Java有哪些数据类型switc...

我以为我学懂了数据结构,直到看了这个导图才发现,我错了

数据结构与算法思维导图

String s = new String(" a ") 到底产生几个对象?

老生常谈的一个梗,到2020了还在争论,你们一天天的,哎哎哎,我不是针对你一个,我是说在座的各位都是人才! 上图红色的这3个箭头,对于通过new产生一个字符串(”宜春”)时,会先去常量池中查找是否已经有了”宜春”对象,如果没有则在常量池中创建一个此字符串对象,然后堆中再创建一个常量池中此”宜春”对象的拷贝对象。 也就是说准确答案是产生了一个或两个对象,如果常量池中原来没有 ”宜春” ,就是两个。...

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

Linux面试题(2020最新版)

文章目录Linux 概述什么是LinuxUnix和Linux有什么区别?什么是 Linux 内核?Linux的基本组件是什么?Linux 的体系结构BASH和DOS之间的基本区别是什么?Linux 开机启动过程?Linux系统缺省的运行级别?Linux 使用的进程间通信方式?Linux 有哪些系统日志文件?Linux系统安装多个桌面环境有帮助吗?什么是交换空间?什么是root帐户什么是LILO?什...

Linux命令学习神器!命令看不懂直接给你解释!

大家都知道,Linux 系统有非常多的命令,而且每个命令又有非常多的用法,想要全部记住所有命令的所有用法,恐怕是一件不可能完成的任务。 一般情况下,我们学习一个命令时,要么直接百度去搜索它的用法,要么就直接用 man 命令去查看守冗长的帮助手册。这两个都可以实现我们的目标,但有没有更简便的方式呢? 答案是必须有的!今天给大家推荐一款有趣而实用学习神器 — kmdr,让你解锁 Linux 学习新姿势...

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

史上最全的 python 基础知识汇总篇,没有比这再全面的了,建议收藏

网友们有福了,小编终于把基础篇的内容全部涉略了一遍,这是一篇关于基础知识的汇总的文章,请朋友们收下,不用客气,不过文章篇幅肯能会有点长,耐心阅读吧爬虫(七十)多进程multiproces...

讲一个程序员如何副业月赚三万的真实故事

loonggg读完需要3分钟速读仅需 1 分钟大家好,我是你们的校长。我之前讲过,这年头,只要肯动脑,肯行动,程序员凭借自己的技术,赚钱的方式还是有很多种的。仅仅靠在公司出卖自己的劳动时...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

85后蒋凡:28岁实现财务自由、34岁成为阿里万亿电商帝国双掌门,他的人生底层逻辑是什么?...

蒋凡是何许人也? 2017年12月27日,在入职4年时间里,蒋凡开挂般坐上了淘宝总裁位置。 为此,时任阿里CEO张勇在任命书中力赞: 蒋凡加入阿里,始终保持创业者的冲劲,有敏锐的...

总结了 150 余个神奇网站,你不来瞅瞅吗?

原博客再更新,可能就没了,之后将持续更新本篇博客。

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

新一代神器STM32CubeMonitor介绍、下载、安装和使用教程

关注、星标公众号,不错过精彩内容作者:黄工公众号:strongerHuang最近ST官网悄悄新上线了一款比较强大的工具:STM32CubeMonitor V1.0.0。经过我研究和使用之...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

大学一路走来,学习互联网全靠这几个网站,最终拿下了一把offer

大佬原来都是这样炼成的

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

为什么你不想学习?只想玩?人是如何一步一步废掉的

不知道是不是只有我这样子,还是你们也有过类似的经历。 上学的时候总有很多光辉历史,学年名列前茅,或者单科目大佬,但是虽然慢慢地长大了,你开始懈怠了,开始废掉了。。。 什么?你说不知道具体的情况是怎么样的? 我来告诉你: 你常常潜意识里或者心理觉得,自己真正的生活或者奋斗还没有开始。总是幻想着自己还拥有大把时间,还有无限的可能,自己还能逆风翻盘,只不是自己还没开始罢了,自己以后肯定会变得特别厉害...

什么时候跳槽,为什么离职,你想好了么?

都是出来打工的,多为自己着想

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

你期望月薪4万,出门右拐,不送,这几个点,你也就是个初级的水平

先来看几个问题通过注解的方式注入依赖对象,介绍一下你知道的几种方式@Autowired和@Resource有何区别说一下@Autowired查找候选者的...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

立即提问
相关内容推荐