Question

In my JavaFX stand alone application, it will get null value when I @Autowired some Service class to JavaFX Controller (with @Component annotation). My code is as below and some one can please help me. Thanks a lot.

Dao Class

package com.core.repository;

public interface DeviceDao extends PagingAndSortingRepository<Device, Integer>, JpaSpecificationExecutor<Device> {

    Device findById(Integer id);

    Device findByName(String name);

    List<Device> findAll();
}

Service class

package com.core.service.impl;

@Service("deviceService")
public class DeviceServiceImpl implements DeviceService {

    @Autowired
    private DeviceDao deviceDao;

    public List<Device> selectAll() {
        return deviceDao.findAll();
    }
}

JavaFX Controller with @Component annotation

package com.stportal.ui.contoller;

@Component
public class HomeController implements Initializable {

    @Autowired
    private DeviceService deviceService;  

    @Override
    public void initialize(URL url, ResourceBundle rb) {

        // This condition will not execute due to service was null 
        if(deviceService != null) {
           System.out.println("Not Null");
        }
     }
}

application-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:beans="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
                ">

    <context:component-scan base-package="com" />
    <context:annotation-config/>

    <bean id="entityManagerFactory"
          class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter" />
        <property name="packagesToScan" value="com.core.domain" />
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
                <!--dialect for MySQL Server-->
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <!--<prop key="hibernate.hbm2ddl.auto">create</prop>-->
                <prop key="hibernate.show_sql">false</prop>
                <prop key="hibernate.format_sql">false</prop>
                <prop key="hibernate.use_sql_comments">false</prop>
            </props>
        </property>
    </bean>

    <bean id="hibernateJpaVendorAdapter"
          class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
    </bean>

    <jpa:repositories base-package="com"
                      transaction-manager-ref="transactionManager"
                      entity-manager-factory-ref="entityManagerFactory" />

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


    <tx:annotation-driven transaction-manager="transactionManager"
                          proxy-target-class="true" />

    <context:property-placeholder
            ignore-resource-not-found="true" location="classpath*:/project.properties" />

    <!-- DataSource Related Configurations -->
    <beans:bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <!--configuration pool via c3p0-->
        <beans:property name="driverClass" value="${jdbc.driver}"/>
        <beans:property name="jdbcUrl" value="${jdbc.url}"/>
        <beans:property name="user" value="${jdbc.username}"/>
        <beans:property name="password" value="${jdbc.password}"/>
        <beans:property name="description" value="integration_ds"/>
        <!--seconds -->
        <beans:property name="acquireIncrement" value="${datasource.acquireIncrement}"/>
        <beans:property name="idleConnectionTestPeriod" value="${datasource.idleConnectionTestPeriod}"/>
        <!--configuration pool via c3p0-->
        <beans:property name="maxPoolSize" value="${datasource.maxPoolSize}"/>
        <beans:property name="maxStatements" value="${datasource.maxStatements}"/>
        <beans:property name="minPoolSize" value="${datasource.minPoolSize}"/>
        <beans:property name="initialPoolSize" value="${datasource.initialPoolSize}"/>
        <beans:property name="maxIdleTime" value="${datasource.maxIdleTime}"/>
        <beans:property name="acquireRetryAttempts" value="${datasource.acquireRetryAttempts}"/>
        <beans:property name="acquireRetryDelay" value="${datasource.acquireRetryDelay}"/>
        <beans:property name="breakAfterAcquireFailure" value="${datasource.breakAfterAcquireFailure}"/>
    </beans:bean>

</beans>

Maven pom.xml file

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <!-- Configure module specific parameters -->
    <groupId>com</groupId>
    <artifactId>IDEW</artifactId>
    <version>1.0</version>
    <packaging>jar</packaging>
    <name>IDEW</name>
    <url>http://maven.apache.org</url>

    <!-- Configure dependency specific properties -->
    <properties>
        <java-version>1.7</java-version>
        <org.springframework-version>4.0.2.RELEASE</org.springframework-version>

        <spring.version>4.0.2.RELEASE</spring.version>
        <hibernate.version>4.3.1.Final</hibernate.version>
        <aspectj.version>1.7.3</aspectj.version>
        <spring-data-jpa.version>1.4.2.RELEASE</spring-data-jpa.version>
        <hibernate-validator.version>5.0.2.Final</hibernate-validator.version>
        <slf4j.version>1.7.5</slf4j.version>
        <logback.version>1.1.0</logback.version>
        <commons-lang3.version>3.2.1</commons-lang3.version>
        <commons-io.version>2.4</commons-io.version>
        <junit.version>4.11</junit.version>            
        <ehcache.version>2.6.8</ehcache.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

    </properties>

    <!-- Configure all dependencies -->
    <dependencies>

        <!-- JavaFX -->
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>javafx</artifactId>
            <version>2.2</version>
            <scope>system</scope>
            <systemPath>${java.home}/lib/jfxrt.jar</systemPath>
        </dependency>

        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>

        <!-- CGLIB (required for Spring annotation configuration) -->
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>${aspectj.version}</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>${aspectj.version}</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${logback.version}</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>log4j-over-slf4j</artifactId>
            <version>${slf4j.version}</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>${slf4j.version}</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jul-to-slf4j</artifactId>
            <version>${slf4j.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>${spring-data-jpa.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>junit</groupId>
                    <artifactId>junit-dep</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-c3p0</artifactId>
            <version>4.3.1.Final</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.29</version>
        </dependency>

    </dependencies>

    <!-- Build specific configurations -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>${java-version}</source>
                    <target>${java-version}</target>
                    <fork>true</fork>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <configuration>
                    <classpathScope>compile</classpathScope>
                    <mainClass>com.stportal.app.MainApplication</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

No correct solution

OTHER TIPS

I know little about Spring, but Koen Serneels wrote a nice blog on Spring and JavaFX integration. The magic key to getting the dependency injection in Spring to work together with JavaFX controllers is to set a controller factory on the FXMLLoader.

Here is a quick sketch of the relevant loading code using Java 8 syntax (I haven't tested it as I don't use Spring - if it doesn't work, please edit the post and correct it if you can).

import java.io.*;
import javafx.fxml.FXMLLoader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class SpringFxmlLoader {
    private static final ApplicationContext applicationContext =
            new AnnotationConfigApplicationContext(
                    SpringApplicationConfig.class
            );

    public Object load(String url) throws IOException {
        FXMLLoader loader = new FXMLLoader();

        loader.setControllerFactory(
                (clazz) -> applicationContext.getBean(clazz)
        );

        return loader.load(
                SpringFxmlLoader.class.getResourceAsStream(url)
        );
    }
}

Even it was not @Autowired, it was fine when I get that service form the Application context.

    @Component
    public class HomeController implements Initializable {

        private DeviceService deviceService;

        @Override
        public void initialize(URL url, ResourceBundle rb) {

          deviceService = AppUtil.appContext.getBean(DeviceService.class);

          // Now this condition is execute due to service was NOT null 
          if(deviceService != null) {
             System.out.println("Not Null");
          }         
       }    
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top