我目前使用@SpringBootApplication进行Spring应用程序设置,但是一切正常,我无法使用自动装配注入xml中定义的bean .
如果我通过xml配置定义依赖注入,注入工作就像
<bean id="dao" class="com.elevations.dao.Dao">
<property name="dataSource" ref="dataSource"/>
</bean>
但是,如果我用@ComponentScanning(“Elevations”)表示我的应用程序,(高程是我的基础包)自动装配工作,然而我的控制器 endpoints 停止工作 . 为什么会这样?
我的应用程序com.elevations.Application定义为
@SpringBootApplication
public class Application
{
public static void main( String[] args )
{
SpringApplication.run( Application.class, args );
ApplicationContext context = new ClassPathXmlApplicationContext( "context.xml" );
}
}
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: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">
<context:component-scan base-package="com.elevations.dao"/>
<!--postgresql jdbc bean-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" autowire="byType">
<property name="driverClassName" value="org.postgresql.Driver"/>
<property name="url" value="jdbc:postgresql://localhost:5432/elevationdb"/>
<property name="username" value="postgres"/>
<property name="password" value=""/>
</bean>
<bean id="dao" class="com.elevations.dao.Dao"/>
</beans>
测试类我试图自动装配com.elevations.dao.Dao
@Component
public class Dao
{
private DataSource m_dataSource;
@Autowired
public void setDataSource( DataSource dataSource )
{
m_dataSource = dataSource;
}
}
控制器com.elevations.controllers.ApplicationController
@Controller
public class ApplicationController
{
@RequestMapping( value = "/elevations", method = RequestMethod.GET )
public String pageGet()
{
return "elevationMaps";
}
@RequestMapping( value = "/elevationData", method = RequestMethod.GET )
@ResponseBody
public LatLng mapGet( @RequestParam( "bounds" ) String bounds, @RequestParam( "diameter") String diameter )
{
JsonParser parser = new JsonParser();
JsonElement viewBounds = parser.parse( bounds );
return new LatLng( 1, 0 );
}
}
1 回答
如果要将xml add
@ImportResource
添加到应用程序类中 .但是我强烈建议放弃你的xml,只需添加一个
application.properties
到src/main/resources
并添加以下属性 .然后从您的 class 中删除
@ImportResource
并重新启动 .