Java 自动装配:预计至少有 1 个 bean 有资格作为此依赖项的自动装配候选者
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44149690/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Autowiring :expected at least 1 bean which qualifies as autowire candidate for this dependency
提问by User-8017771
Okay, I know that there are many questions asked around the same topic. But I cant seem to make anything work. It also might be the case that I am yet to completely understand the auto wiring concept. My Problem: I am able to get to the required page, but whenever I click on the any button to perform an action I get Null pointer exception which seems obvious as I dont think spring is able to properly map the bean needed.
好的,我知道围绕同一主题提出了很多问题。但我似乎无法使任何工作。也可能是我还没有完全理解自动布线的概念。我的问题:我能够到达所需的页面,但是每当我单击任何按钮执行操作时,我都会收到 Null 指针异常,这似乎很明显,因为我认为 spring 无法正确映射所需的 bean。
So, when I add @autowired=true , it gives me the above given exceptionn. I am not sure what needs to be done.. Hope someone can help me out with this. Would love an explanation as well:) Code:
所以,当我添加 @autowired=true 时,它给了我上面给出的异常。我不确定需要做什么.. 希望有人能帮我解决这个问题。也希望得到解释:) 代码:
@Entity
@Table(name="userDetails")
public class UserDetailModel {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public int user_id;
public String password;
public String user_name;
public String active_status;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public String getActive_status() {
return active_status;
}
public void setActive_status(String active_status) {
this.active_status = active_status;
}
}
}
Controller:
控制器:
@RestController
public class UserDetailController {
private Logger logger = (Logger) LoggerFactory.getLogger(UserDetailController.class);
@Autowired(required = true)
private UserRepository userRepository;
@RequestMapping(value="/login", method = RequestMethod.POST)
public @ResponseBody String addNewUser (@RequestBody UserDetailModel user) {
// @ResponseBody means the returned String is the response, not a view name
// @RequestParam means it is a parameter from the GET or POST request
logger.debug("in controller");
UserDetailModel userDtl = new UserDetailModel();
userDtl.setUser_id(user.user_id);
userDtl.setUser_name(user.user_name);
userDtl.setActive_status(user.active_status);
userDtl.setPassword(user.password);
userRepository.save(userDtl);
return "Saved";
}
}
}
Repository:
存储库:
@Repository
public interface UserRepository extends CrudRepository<UserDetailModel, Long> {}
Stack Trace:
堆栈跟踪:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDetailController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.springBoot.usl.repo.UserRepository com.springBoot.usl.controller.UserDetailController.userRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.springBoot.usl.repo.UserRepository] 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:292)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:120)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:683)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:313)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:944)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:933)
at com.springBoot.usl.controller.WebAppInitializer.main(WebAppInitializer.java:18)
Solved based on the responsesAnswer:I made some modifications based on Jay and Luay's answers. And changed the annotations as follows in my ApplicationConfig file:
根据回复解决答:我根据 Jay 和 Luay 的回答做了一些修改。并在我的 ApplicationConfig 文件中按如下方式更改了注释:
@Configuration
@ComponentScan("my.basepackage.*")
@EnableJpaRepositories(basePackages = {"my.basepackage.*"})
@EntityScan("my.basepackage.*")
@EnableAutoConfiguration
Hope this helps some one.
希望这对某人有所帮助。
But I am not sure if * is the right way to go.
但我不确定 * 是否是正确的方法。
回答by Jay Smith
You need to enable the JPA repositories in your config class, specify the package that contains the repositories as below
您需要在配置类中启用 JPA 存储库,指定包含存储库的包,如下所示
@Configuration
@EnableJpaRepositories(basePackages = {
"com.springBoot.usl.repo"
})
public class ApplicationConfig {
}
Example of ApplicationConfig:
应用配置示例:
@Configuration
@EnableJpaRepositories(basePackages = {"com.springBoot.usl.repo"})
@EnableTransactionManagement
public class ApplicationConfig {
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/xxxx");
dataSource.setUsername("xxxx");
dataSource.setPassword("xxxx");
return dataSource;
}
@Bean
public EntityManagerFactory entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("xx.xxxx.xxxx.xxxx.domain");
factory.setDataSource(dataSource());
factory.afterPropertiesSet();
return factory.getObject();
}
@Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory());
return txManager;
}
回答by Naresh Joshi
I think your application is not able to scan the UserRepository
class, If you are using Spring Boot then you should put the main class on top of your package hierarchy.
我认为您的应用程序无法扫描UserRepository
类,如果您使用的是 Spring Boot,那么您应该将主类放在包层次结构的顶部。
You should also use @EnableJpaRepositories
and tell it the base package of your repos to enable the repository functionality
您还应该使用@EnableJpaRepositories
并告诉它您的存储库的基本包以启用存储库功能
@EnableJpaRepositories(basePackages ={"com.springBoot.usl.repo"})
@EnableJpaRepositories(basePackages ={"com.springBoot.usl.repo"})
回答by Luay Abdulraheem
UserRepository
is simply not defined in the current Spring Context.
Make sure that your class is defined in a package that is scanned by Spring. You will need to use @ComponentScan("org.my.pkg")
in your Configuration class to make Spring scan the package.
UserRepository
根本没有在当前的 Spring 上下文中定义。确保您的类定义在 Spring 扫描的包中。您将需要@ComponentScan("org.my.pkg")
在您的 Configuration 类中使用以使 Spring 扫描包。
If you're using Spring Boot, make sure you locate your main application class which is annotated with @SpringBootApplication
in a root package above other classes, as it contains @ComponentScan
.
如果您使用的是 Spring Boot,请确保您@SpringBootApplication
在其他类上方的根包中找到了注释的主应用程序类,因为它包含@ComponentScan
.
回答by RoshanKumar Mutha
I am able to run your application with some changes on annotation side.
我能够在注释方面进行一些更改来运行您的应用程序。
I have used same classes which are given in question. Please see below structure and configuration used. Directory Structure
我使用了有问题的相同课程。请参阅下面使用的结构和配置。 目录结构
I have used packages as below and added your classes,
com.rcmutha.usl.controller
com.rcmutha.usl.repository
我使用了如下包并添加了你的类,
com.rcmutha.usl.controller
com.rcmutha.usl.repository
@SpringBootApplication
@ComponentScan({"com.rcmutha*"})
@EntityScan("com.rcmutha*")
@EnableJpaRepositories("com.rcmutha*")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
For complete code : click here for code
完整代码: 点击这里获取代码
回答by Wellington DC
I know that the problem was solved, but as it can be problem for someone else like I had, I decided to share my problem and the solution. I got exactly the same error message, but the problem was the lack of the annotation @Service in a classand hence an object of this type couldn't autowire. After putting this annotation, everything worked fine.
我知道问题已经解决了,但是对于像我这样的其他人来说可能是个问题,我决定分享我的问题和解决方案。我得到了完全相同的错误消息,但问题是类中缺少 @Service 注释,因此这种类型的对象无法自动装配。放置此注释后,一切正常。
Below is the object of the mentioned class:
下面是上述类的对象:
@Autowired
private JwtUserDetailsService jwtUserDetailsService;
Just this annotation caused the same problem and can pass unnoticed:
只是这个注释引起了同样的问题,并且可能会被忽视:
@Service // annotation that was missing
public class JwtUserDetailsService implements UserDetailsService { ...