Tzu ng
Tzu ng

Reputation: 9244

Spring3 - @Autowired

This is my applicationContext.xml

<bean id="JdbcUserDao" class="controller.User.JdbcUserDao">
    <property name="dataSource" ref="dataSource"/>
</bean>


<bean id="dataSource"
      class="org.springframework.jdbc.datasource.DriverManagerDataSource"
      p:driverClassName="org.apache.derby.jdbc.ClientDriver"
      p:url="jdbc:derby://localhost:1527/TodoDb"
      p:username="root"
      p:password="root" />

This is my implDao class :

@Repository
public class JdbcUserDao implements IUserDao {

    private JdbcTemplate jt;
    @Autowired
    private DataSource dataSource;

    public DataSource getDataSource() {
        return dataSource;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
            jt = new JdbcTemplate(this.dataSource); 
    }

    public JdbcTemplate getJt() {
        return jt;
    }

    public void setJt(JdbcTemplate jt) {
        this.jt = jt;
    }


    @Override
    public List<User> getUsers(final String username, final String password) {
        List<User> users = this.jt.query("SELECT username, password FROM USERS",
            new RowMapper<User>() {

                @Override
                public User mapRow(ResultSet rs, int i) throws SQLException {
                    User user = new User();
                    user.setUsername(rs.getString("username"));
                    user.setPassword(rs.getString("password"));
                    return user;
                }
            });
        return users;
    }
}

Problems:

Questions:

  1. How can I get this works ?

I'm new to spring3 so I really need your help.

Upvotes: 0

Views: 2212

Answers (4)

Vivek Chaudhari
Vivek Chaudhari

Reputation: 2010

you need to import the class which you are doing autowired without access modifiers in repository class file

com.<your project>.controller.User.JdbcUserDao

and spring annotation

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.CrudRepository;
@Repository
 public class JdbcUserDao implements IUserDao {

  @Autowired
  DataSource dataSource;

Upvotes: 0

Angus
Angus

Reputation: 128

You could try adding the autowire to the set method instead of the property.

Upvotes: 0

Shaun Hare
Shaun Hare

Reputation: 3871

Try adding the AutowiredPostProcessor to the config

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor">
 </bean>

Upvotes: 1

danny.lesnik
danny.lesnik

Reputation: 18639

In order to use autowiring, you need to add the following to your xml file configuration.

<context:annotation-config />

If it doesn't help then please add

<context:component-scan base-package="org.springframework.jdbc.datasource" />

Upvotes: 2

Related Questions