我使用配置类创建了Spring Boot应用程序。通常使用Spring库的RestAPI。在其中我使用我自己的Logger类来记录每个动作。
另外,我在我的Application类中包含application.properties,其中是main函数。 xml中没有bean - 仅在该Configuration类中的所有内容。
以下是该配置:
@SpringBootConfiguration
public class ApplicationConfiguration {
@Value("${hibernate.dialect}")
private String dialect;
@Value("${hibernate.show_sql}")
private String showSql;
@Value("${hibernate.mappingResources}")
private String[] mappingResources;
@Value("${jdbc.driverClassName}")
private String driverClassName;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Autowired
private DataSource dataSource;
@Autowired
private LocalSessionFactoryBean localSessionFactoryBean;
@Bean
public LocalSessionFactoryBean localSessionFactoryBean() {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource);
Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.dialect", dialect);
hibernateProperties.setProperty("hibernate.show_sql", showSql);
sessionFactoryBean.setHibernateProperties(hibernateProperties);
sessionFactoryBean.setMappingResources(mappingResources);
return sessionFactoryBean;
}
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(driverClassName);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
}
另外,我创建了logger类:
@Service
public class LinksLogger {
private static final Logger logger = Logger.getLogger("MyLogs");
// methods here...
}
这是我如何使用我的记录器:
@RestController
@RequestMapping("/api/v1")
public class HelloController {
@Autowired
private LinksLogger logger;
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public Map<String, String> hello() {
Map<String, String> data = new HashMap<>();
data.put("data", "Hello#_#World");
logger.log("Hello#_#World");
return data;
}
}
看起来好像,对吗? 但是当我编译我的代码时,我得到了异常:
There is a circular dependency between 2 beans in the application context:
- helloController (field private com.defaultxyz.linksapi.util.LinksLogger com.defaultxyz.linksapi.controller.HelloController.logger)
- applicationConfiguration (field private org.springframework.orm.hibernate3.LocalSessionFactoryBean com.defaultxyz.linksapi.util.ApplicationConfiguration.localSessionFactoryBean)
- localSessionFactoryBean
为什么出现此异常?我在代码中做错了什么?
答案 0 :(得分:5)
你正试图在实例化它们的类中使用@Autowire bean。
@Autowired
private DataSource dataSource;
@Autowired
private LocalSessionFactoryBean localSessionFactoryBean;
但是你也将它们定义为@Bean,容器不能将它们注入到自动装配的字段中,因为它们是在同一个类中创建的。删除@Autowired字段,改为使用所需的方法。
sessionFactoryBean.setDataSource(dataSource());
而不是
sessionFactoryBean.setDataSource(dataSource);