在spring引导应用程序中使用@bean的java声明bean
我刚刚开始使用Spring(Boot)
我在abc.de
中有我的“main”类,用@SpringApplication
注释
到目前为止,一切正常。我只使用了刻板印象注释
现在我想将@Bean
与@Configuration
类一起使用,看看它是如何工作的
我的@Configuration
类:
@Configuration
public class BeanConfiguration {
@Bean
public XslDataFileLoader dataSource() {
return new XslDataFileLoader();
}
}
类XslDataFileLoader
在同一个包中
我在控制器类中用@Autowired
声明这个bean
所以我的“main”类在abc.de
中,config类在abc.de.config
中,XslDataFileLoader也在abc.de.config
中
当我启动应用程序时,spring无法注入bean。它找不到
我试过scanPackages = abc.de.config
:这样,我的其他豆子就找不到了
我需要如何在最新的春季战靴中声明这一点
编辑
Stacktrace:
2017-05-19 13:52:03 ERROR o.s.b.d.LoggingFailureAnalysisReporter -
***************************
APPLICATION FAILED TO START
***************************
Description:
Field dataSource in abc.de.controllers.LoginController required a bean of type 'abc.de.config.XslDataFileLoader' that could not be found.
Action:
Consider defining a bean of type 'abc.de.config.XslDataFileLoader' in your configuration.
XslDataFileLoader:
package abc.de.config;
public class XslDataFileLoader {
public XslDataFileLoader() {
}
}
登录控制器:
package abc.de.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import abc.de.config.XslDataFileLoader;
@Controller
public class LoginController {
@Autowired
XslDataFileLoader loader;
@GetMapping("/login")
public String login() {
System.out.println(loader);
return "login";
}
@PostMapping("/login")
public String loginTry() {
return "redirect:dashboard";
}
}
第二次编辑
MySpringBootApplication:
package abc.de;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@SpringBootApplication
@EnableJpaRepositories
public class MySpringBootApplication{
public static void main(final String[] args) {
SpringApplication.run(MySpringBootApplication.class, args);
}
}
应用程序。属性:
server.port=5566
spring.application.name=@project.name@
# data source
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/springboot
spring.datasource.username=root
spring.datasource.password=
# Session
spring.session.store-type=none
# Security
security.basic.enabled=false
# logging
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n
logging.level.org.hibernate.SQL=debug
#logging.level.org.hibernate.type.descriptor.sql=trace
logging.level.=error
# 1 楼答案
首先,请发布所有代码和stacktrace
BeanConfiguration
类配置正确,因此您的注入可能有问题你有关于
XslDataFileLoader
类的注释吗?这可能是一个双bean声明和not bean not found的问题(如果您在XslDataFileLoader
上有一个@Component
,同时在BeanConfiguration
中声明了它)