Spring构造函数注入,无法注入的问题

手动配置bean主要与web中的一个配置目录相关
< context-param >
< param-name > contextConfigLocation </ param-name >
< param-value >
classpath:spring-mybatis.xml
</ param-value >
</ context-param >
上面配置的作用是:<!-- 指定Spring Bean的配置文件所在目录。默认配置在WEB-INF目录下 -->
< param-value >的内容可以是1个,也可以是多个,中间用逗号隔开

之所以自己在 spring-mvc.xml中配置bean一直无法正常注入,就是因为这里的 < param-value >中没有 spring-mvc.xml,自己尝试在spring-mybatis.xml中配置,可正常注入,因此就翻看web.xml的配置。
尝试修改SpringMVC的开启顺序, < load-on-startup > 1 </ load-on-startup >,将1改为0,还是不行。
然后尝试,将 spring-mvc.xml也加入到contextConfigLocation配置中,就可以正常注入了。
如下
< context-param >
< param-name > contextConfigLocation </ param-name >
< param-value >
classpath:spring-mybatis.xml, classpath:spring-mvc.xml
</ param-value >
</ context-param >

报错信息如下:
ERROR] [org.springframework.web.context.ContextLoader] Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'taskJob': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean found for dependency [pubinfo.controller.TestCons]: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@javax.annotation.Resource(mappedName=, shareable=true, description=, name=, type=class java.lang.Object, authenticationType=CONTAINER, lookup=)}

在Java Spring框架中,构造函数注入是依赖注入的一种方式,它通过构造函数为对象提供依赖。为了使用构造函数注入,你需要定义一个带有依赖项作为参数的构造函数,并使用@Autowired注解或构造器注入的Java配置。以下是一个使用构造函数注入的简单例子: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class MyService { private final MyDependency myDependency; // 使用@Autowired注解进行构造函数注入 @Autowired public MyService(MyDependency myDependency) { this.myDependency = myDependency; } // ... 其他方法 ... } ``` 在这个例子中,`MyService` 有一个名为 `myDependency` 的依赖项,它通过构造函数注入。`@Autowired` 注解告诉Spring框架,当创建 `MyService` 的实例,需要传入一个 `MyDependency` 型的依赖项。Spring会自动寻找合适的 `MyDependency` 型的bean,或者如果这个型只有一个定义的bean,则自动注入。 另外,如果是在Java配置中,也可以使用`@Autowired`注解直接在构造函数上,但更多候使用`@Bean`注解方法,这样更灵活,可以进行复杂的bean配置。 ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class AppConfig { @Bean public MyService myService() { return new MyService(myDependency()); } @Bean public MyDependency myDependency() { return new MyDependency(); } } ``` 在上面的配置`AppConfig`中,`myService()`方法定义了一个bean,其构造函数注入了由`myDependency()`方法创建的`MyDependency`实例。这种方式下,使用构造函数注入并不需要在方法上使用`@Autowired`注解,因为通过方法返回型和方法名,Spring可以解析依赖关系。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值