java - Autowiring required beans -
i trying wire beans using annotations.. when beans not present in beans.xml config file, getting null pointer exception.. expect required=false attribute fix this.. fair expectation? if so, why still throwing exception if set required false missing bean...
package com.rajkumar.spring; import org.springframework.beans.factory.annotation.autowired; public class log { private consolewriter consolewriter; private filewriter filewriter; @autowired public void setconsolewriter(consolewriter consolewriter) { this.consolewriter = consolewriter; } @autowired(required=false) public void setfilewriter(filewriter filewriter) { this.filewriter = filewriter; } public void writetofile(string message) { filewriter.write(message); // throwing error bean comments in xml file.. } public void writetoconsole(string message) { consolewriter.write(message); } }
my beans.xml below..
<?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:context="http://www.springframework.org/schema/context" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <bean id="log" class="com.rajkumar.spring.log"></bean> <bean id="consolewriter" class="com.rajkumar.spring.consolewriter"> </bean> <!-- <bean id="filewriter" class="com.rajkumar.spring.filewriter"></bean> --> <context:annotation-config></context:annotation-config> </beans>
required=false
make spring container dependency checking optional , avoids correpsonding bean not found exception like.. required bean of type 'com.rajkumar.spring.filewriter' not found.
please note injected object still null
here, hence seeing nullpointerexception
.
hope helps you.
Comments
Post a Comment