@Autowired with @Qualifier不起作用

时间:2016-10-12 09:18:53

标签: java spring spring-annotations

我遇到@Autowired和@Qualifier注释的问题。我想创建这个类的对象:

public class DatabaseUtils {
private String driver, url, username, password;

public void setDriver(String driver) { this.driver = driver; }
public void setUrl(String url) { this.url = url; }
public void setUsername(String username) { this.username = username; }
public void setPassword(String password) { this.password = password; } }

使用@Autowired和@Qualifier注释:

@ContextConfiguration(locations = {"/beans.xml"}) public abstract class AbstractTest {

@Autowired
@Qualifier("dataBase")
public static DatabaseUtils db; }

但是因为db我在调试期间得到了null。但是,当我将使用这样的结构时:

ApplicationContext context = new ClassPathXmlApplicationContext("/beans.xml");
    db = (DatabaseUtils)context.getBean("dataBase");
一切都很好。一些建议? 这是xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans default-init-method="true"
   xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"
   default-lazy-init="true">

<bean id="dataBase" class="uk.co.coral.DatabaseUtils">
    <property name="driver" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost/sports_data"/>
    <property name="username" value="root"/>
    <property name="password" value=""/>
</bean>

0 个答案:

没有答案