P
P
P_Alexander2018-06-06 19:58:27
Java
P_Alexander, 2018-06-06 19:58:27

Why doesn't the @Autowired annotation throw nullPointerException?

I started to study the spring, wrote a tao layer and decided to test it, I'm catching zero help.
It seems that I annotated and registered everything, but I can’t understand why it doesn’t work.
Spring: db-config-test.xml

<context:component-scan base-package="com"/>
    <context:property-placeholder location="classpath:application.properties"/>
    <bean id="basicDataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <bean name="hibernateJpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
    <bean id="entityManagerFactoryBean" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter"/>
        <property name="dataSource" ref="basicDataSource"/>
        <property name="persistenceUnitName" value="myJpaPersistenceUnit"/>
        <property name="packagesToScan">
            <list>
                <value>com.model</value>
            </list>
        </property>
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
            </props>
        </property>
    </bean>
    <bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactoryBean"/>
    </bean>
    <tx:annotation-driven transaction-manager="txManager"/>

Model
@Entity
@Table(name = "role", schema = "spring_t", uniqueConstraints = {@UniqueConstraint(columnNames = "id_role")})
public class Role implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @Column(name = "id_role")
    private Integer id_role;
    @NotEmpty
    @Size(min = 5, max = 15)
    @Column(name = "name_role", length = 15, unique = false, nullable = false)
    private String name_role;
    @OneToMany(mappedBy = "role", cascade = CascadeType.ALL)
    private Set<User> users = new HashSet<User>();
    public Role() {}
}

AbstractDAO
public abstract class AbstractDAO<PK extends Serializable, T> {
    private final Class<T> persistentClass;
    @SuppressWarnings("unchecked")
    public AbstractDAO(){
        this.persistentClass =(Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1];
    }
    @PersistenceContext
    private EntityManager entityManager;
    protected EntityManager getEntityManager(){
        return this.entityManager;
    }
    protected T getByKey(PK key){
        return (T) entityManager.find(persistentClass, key);
    }
    protected void persist (T entity){
        entityManager.persist(entity);
    }
    protected void update(T entity){
        entityManager.merge(entity);
    }
    protected void delete(T entity){
        entityManager.remove(entity);
    }
}

Role DAO
public interface RoleDAO {
    List<Role> findAllRoles();
    Role findByRoleName(String roleName);
    Role findById(int id);
    void save(Role role);
}

RoleDAOImpl
@Repository("RoleDAO")
public class RoleImpl extends AbstractDAO<Integer, Role> implements RoleDAO{
    @SuppressWarnings("unchecked")
    @Override
    public List<Role> findAllRoles() {
        List<Role> roles =  getEntityManager()
                .createQuery("SELECT r FROM Role r ORDER BY r.name_role ASC")
                .getResultList();
        return roles;
    }
    @Override
    public Role findByRoleName(String roleName) {
        try {
            Role role = (Role) getEntityManager()
                    .createQuery("SELECT r FROM Role r WHERE r.name_role LIKE :name_role")
                    .setParameter("name_role", roleName)
                    .getSingleResult();
            return role;
        }catch (NoResultException e){
            return null;
        }
    }
    @Override
    public Role findById(int id) {
        return getByKey(id);
    }
    @Override
    public void save(Role role) {
        persist(role);
    }
}

Role Service
public interface RoleService {
    List<Role> findAllRoles();
    Role findByRoleName(String roleName);
    Role findById(int id);
    void saveRole(Role role);
}

RoleServiceImpl
@Service("RoleService")
@Transactional
public class RoleServiceImpl implements RoleService{
    @Autowired
    private RoleDAO roleDAO;
    @Override
    public List<Role> findAllRoles() {
        return roleDAO.findAllRoles();
    }
    @Override
    public Role findByRoleName(String roleName) {
        Role role = roleDAO.findByRoleName(roleName);
        return role;
    }
    @Override
    public Role findById(int id) {
        Role role = roleDAO.findById(id);
        return role;
    }
    @Override
    public void saveRole(Role role) {
        roleDAO.save(role);
    }
}

TestClass
@ContextConfiguration(locations = "classpath:db-config-test.xml")
@RunWith(SpringJUnit4ClassRunner.class)
class RoleTest {
    @Autowired
    public RoleServiceImpl roleServiceImpl;
    @Test
    @Transactional
    void saveTest() {
        Role role = new Role();
        role.setNameRole("admin");
        Role role1 = new Role();
        role1.setNameRole("user");
        Role role2 = new Role();
        role2.setNameRole("none");
        User user = new User("Alex", "Login",
                "[email protected]", "111111111", LocalDate.now(), role);
        role.getUsers().add(user);
        User user1 = new User("Alex1", "Login1",
                "[email protected]", "222222222", LocalDate.now(), role1);
        role1.getUsers().add(user1);
        User user2 = new User("Alex2", "Login2",
                "[email protected]", "333333333", LocalDate.now(), role2);
        role2.getUsers().add(user2);
        roleServiceImpl.saveRole(role);
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Eugene, 2018-06-07
@P_Alexander

It is difficult to judge without the stacktrace of the error itself, but I dare to suggest that the problem occurs due to the fact that your RoleService is not described in the configuration. At the time of test launch, Spring only reads the configuration from db-config-test.xml, and there is not a word about RoleService in it. From the fact that you put the annotation Service on your implementation, the class did not become a bean in terms of Spring. He [Spring] needs to hint where to look for these same beans, or describe them explicitly in the configuration. As a rule, tests are written with their own configuration, in which only those beans that participate in the test are declared.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question