简体   繁体   中英

Spring not creating bean with boolean in the constructor

I'm trying to create a simple bean passing a file and a boolean in the constructor, as follows:

@Service
public class FileBasedSink implements Sink {
 protected File outputDirectory;
 protected boolean useCompression;

 public FileBasedSink(File outputDirectory, boolean useCompression) {
    this.outputDirectory = outputDirectory;
    this.useCompression = useCompression;

}


}

and the spring-context file:

<context:component-scan base-package="org.aksw.simba.squirrel" />

    <!-- 
        <bean id="workerImpl" class="org.aksw.simba.squirrel.worker.impl.WorkerImpl"></bean>
     -->
    <!-- Output folder for FileBasedSink -->
    <bean id="outputFolder" class="java.io.File">
        <constructor-arg index="0" value="{systemProperties['OUTPUT_FOLDER']}" />
    </bean>

    <!-- File Based Sink implementation -->
    <bean id="fileSink" class="org.aksw.simba.squirrel.sink.impl.file.FileBasedSink">
        <constructor-arg name="outputDirectory" ref="outputFolder" />
        <constructor-arg name="useCompression" value="true"/>
    </bean>

This should be simple, but somehow, spring throws NoSuchBeanDefinitionException : No qualifying bean of type 'boolean' available.

What am i missing here?

You're mixing component-scan and XML bean definitions.

Approach 1:

Use the @Service -annotation, but then add @Autowired to the constructor. Remove the definition of FileBasedSink -bean from XML. If it's a constant boolean bean, then @Value("true") to the boolean param. Or, as suggested by @Obi Wan - PallavJha you can declare the boolean bean somewhere in the context and use the @Qualifier("booleanBean") -annotation for the boolean param.

Approach 2:

Define the bean in XML passing the <constructor-arg's> , but then remove the @Service -annotation.

you need to provide the type of the variable useCompression

<constructor-arg type="boolean">
   <value>true</value>
</constructor-arg>

You can create a bean of boolean type:

<bean id="booleanBean" class="java.lang.Boolean">
    <constructor-arg value="true"/>
</bean>

and then use it as a reference for creating fileSink object, like,

<bean id="fileSink" class="org.aksw.simba.squirrel.sink.impl.file.FileBasedSink">
    <constructor-arg name="outputDirectory" ref="outputFolder" />
    <constructor-arg name="useCompression" ref="booleanBean"/>
</bean>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM