Бин, введенный весной, равен нулю

Я использую Spring Framework / Data / HATEOAS и пытаюсь добавить Dozer.

В моем spring-config.xml есть следующий bean-компонент:

<?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:data="http://www.springframework.org/schema/data/jpa"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
            http://www.springframework.org/schema/data/jpa
            http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-2.5.xsd">

    <bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
        <property name="database" value="POSTGRESQL" />
        <property name="databasePlatform" value="org.hibernate.dialect.PostgreSQLDialect" />
    </bean>

    <bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
        <property name="dataSource" ref="dataSource" />
        <property name="jpaDialect" ref="jpaDialect" />
    </bean>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.postgresql.Driver" />
        <property name="url" value="jdbc:postgresql://localhost:5432/cp" />
        <property name="username" value="cp_user" />
        <property name="password" value="+JMJ+pw0m2d" />
    </bean>

    <context:component-scan base-package="com.mydomain.data.assembler" />
    <data:repositories base-package="com.mydomain.repository" />

    <mvc:annotation-driven />

    <bean id="dozerFactory" class="org.dozer.spring.DozerBeanMapperFactoryBean" scope="singleton">
        <property name="mappingFiles" value="classpath*:/*mapping.xml"/>
    </bean>

</beans>

И следующий ассемблер:

@Component
public class UserResourceAssembler {

    @Inject 
    private Mapper dozerBeanMapper;

    public UserResource toResource(User user) {
        UserResource resource = dozerBeanMapper.map(user, UserResource.class);
        resource.add(linkTo(methodOn(UserController.class).get(user.getId())).withSelfRel());
        return resource;
    }

    public User toEntity(UserResource resource) {
        User user = dozerBeanMapper.map(resource, User.class);
        return user;
    }
}

Итак, - я новичок в бобах и инъекциях - но я предполагаю, что фабричный бин? Предполагается? чтобы ввести Mapper. Но Mapper определенно равен нулю. Я знаю, что делаю это неправильно, но что я делаю неправильно?


person Lurk21    schedule 11.01.2014    source источник


Ответы (2)


Spring вводит свои бобы в управляемые им бобы. Вы используете неуправляемый статический контекст. Также измените UserResourceAssembler на управляемый компонент:

@Component
public class UserResourceAssembler {

    @Inject
    private Mapper dozerBeanMapper;

    public UserResource toResource(User user) {
    }

    public User toEntity(UserResource resource) {
    }

}

См. почему мы не можем автоматически связывать статические поля весной.

person Markus Malkusch    schedule 11.01.2014
comment
Хорошо, это хорошо, я прочитал и этот, и связанный ответ. К сожалению, происходит то же самое. Я обновил вопрос текущим кодом. - person Lurk21; 11.01.2014
comment
Я добавил ‹context: в мою конфигурацию spring, чтобы включить мой пакет ассемблера. По-прежнему никакой радости. - person Lurk21; 11.01.2014

Я бы предпочел что-то подобное. Но потом я прочитал:

Бин запуска Dozer Singleton введен как Null

Это сработало. Вот моя реализация.

Я удалил bean-компонент из spring-config и контекстного сканирования.

Я добавил этот класс:

@Singleton
public class DozerInstantiator {
    public static DozerBeanMapper getInstance(){
        return MapperHolder.instance;
    }

    private static class MapperHolder{
        static final DozerBeanMapper instance = new DozerBeanMapper();
    }
}

И обновил мой ассемблер вот так:

public class UserResourceAssembler {

    private DozerBeanMapper mapper;

    public UserResourceAssembler() {
        mapper = DozerInstantiator.getInstance();
    }

    public UserResource toResource(User user) {     
        UserResource resource = mapper.map(user, UserResource.class);
        resource.add(linkTo(methodOn(UserController.class).get(user.getId())).withSelfRel());
        return resource;
    }

    public User toEntity(UserResource resource) {
        User user = mapper.map(resource, User.class);
        return user;
    }
}
person Lurk21    schedule 11.01.2014