I've this basic spring application in which the value of my #Autowired field is null in output. What is wrong here?
package com.spring;
import org.springframework.beans.factory.annotation.Autowired;
public class HelloWorld {
private String message;
#Autowired
private Double pi;
public HelloWorld(String message){
this.message = message;
}
public void setMessage(String message){
this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
System.out.println("autowired: "+pi);
}
}
spring.xml config file.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="pi" name="pi" class="java.lang.Double" autowire="byName">
<constructor-arg value="3.14"/>
</bean>
<bean id="helloWorld" class="com.spring.HelloWorld">
<constructor-arg ref="msg" />
</bean>
<bean id="msg" class="java.lang.String" >
<constructor-arg value="Hello World"/>
</bean>
</beans>
Class to execute the APP:
package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
HelloWorld hw = context.getBean(HelloWorld.class);
hw.getMessage();
System.out.println(context.getBean("msg"));
}
}
The output is:
Your Message Hello World
autowired: null
Hello World
You need to configure the context to allow autowiring. See this answer:
how do I configure autowire in spring
You need to add <context:annotation-config/> in your spring.xml file which will scan for spring annotations in your java files. Hope this helps.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config />
<bean id="pi" name="pi" class="java.lang.Double">
<constructor-arg value="3.14" />
</bean>
<bean id="helloWorld" class="com.clsa.test.HelloWorld">
<constructor-arg ref="msg" />
</bean>
<bean id="msg" class="java.lang.String">
<constructor-arg value="Hello World" />
</bean>
</beans>
you want to define #Quatifier
#Autowired(required=true)
#Qualifier("pi")
Double pi;
Related
I have a Global Filter with an injected attribute.
public class AuthenticationGlobalFilter implements GlobalFilter, Ordered {
#Autowired
private Permission permission;
#Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
long serviceId = 0;
try {
ServerHttpRequest request = exchange.getRequest();
HttpHeaders headers = request.getHeaders();
String fromKey = headers.getFirst("x-api-key");
String fromIp = headers.getFirst("x-forwarded-for");
String fromSubject = headers.getFirst("******");
URI rqUrl = request.getURI();
String path = rqUrl.getPath();
serviceId = Long.parseLong(path.split("/")[6]);
permission.check(permission.identity(fromKey, fromSubject, fromIp), serviceId);
return chain.filter(exchange);
} catch (PermissionException e) {
exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
} catch (IllegalArgumentException e) {
exchange.getResponse().setStatusCode(HttpStatus.BAD_REQUEST);
} catch (Exception e) {
exchange.getResponse().setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
}
return Mono.empty();
}
}
Injection works perfectly when I run the application
#EnableDiscoveryClient
#SpringBootApplication
#EnableConfigurationProperties(ApiGatewayProperties.class)
#Import({ PermitAllSecurityConfiguration.class, CustomAttributesConfiguration.class })
#ImportResource(value = { "classpath:datasource.xml", "classpath:api-gateway-unico-beans.xml" })
public class ApiGatewayUnicoApplication {
public static void main(String[] args) {
SpringApplication.run(ApiGatewayUnicoApplication.class, args);
}
}
With this configuration file:
<?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:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<cache:annotation-driven
cache-manager="cacheManager" />
<context:annotation-config />
<context:component-scan
base-package="*****.apigatewayunico" />
<bean
class="*****.apigatewayunico.filters.AuthenticationGlobalFilter" />
<bean class="*****.apigatewayunico.Persistence"
p:sql="SELECT rep.url FROM RestService rs, RestEndpoint rep WHERE rep.id = rs.endpoint_id AND rs.id = ? AND rs.available = true" />
<bean id="permission"
class=*****.permission.Permission" />
The problem is that when I make a unit test, the property is injected in the unit test by not in the filter being tested, giving me errors about not being able to locate a bean that can satisfy this dependency.
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = RANDOM_PORT)
#DirtiesContext
public class AuthenticationGlobalFilterIntegrationTests extends BaseWebClientTests {
#Autowired
private Permission permission;
#Before
public void setup() {
super.setup();
reset(permission);
permission.check(null, 123456L);
}
#Test
public void runSucessTest() {
expectLastCall();
replay(permission);
testClient.get().uri("/status/200").exchange().expectStatus().isEqualTo(HttpStatus.OK);
}
#Test
public void runPermissionExceptionTest() throws Exception {
expectLastCall().andThrow(new PermissionException(""));
replay(permission);
testClient.get().uri("/status/200").exchange().expectStatus().isEqualTo(HttpStatus.FORBIDDEN);
}
#EnableAutoConfiguration
#SpringBootConfiguration
#Import(DefaultTestConfig.class)
#ImportResource(value = "classpath:authentication-filter-test-beans.xml")
public static class TestConfig {
}
}
authentication-filter-test-beans.xml:
<?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:c="http://www.springframework.org/schema/c"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="classpath:api-gateway-unico-test-beans.xml" />
<bean id="authenticationFilter"
class="*****.apigatewayunico.filters.AuthenticationGlobalFilter">
</bean>
</beans>
api-gateway-unico-test-beans.xml:
<?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:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"
default-lazy-init="false">
<bean id="mockSupport" class="org.easymock.EasyMockSupport" />
<bean id="pp" factory-bean="mockSupport"
factory-method="createNiceMock"
c:_0="*****.permission.PermissionPersistence" />
<bean id="permission" factory-bean="mockSupport"
factory-method="createNiceMock"
c:_0="*****.permission.Permission" />
<bean id="jdbc" factory-bean="mockSupport"
factory-method="createNiceMock"
c:_0="org.springframework.jdbc.core.JdbcTemplate" />
<bean id="descoveryClienteMock" factory-bean="mockSupport"
factory-method="createNiceMock"
c:_0="org.springframework.cloud.client.discovery.DiscoveryClient" />
<bean id="serviceInstanceMock" factory-bean="mockSupport"
factory-method="createNiceMock"
c:_0="org.springframework.cloud.client.ServiceInstance" />
</beans>
Now when I try to add the unit test's configuration xml to the #ConextConfiguration annotation in the unit test, I get a test related to Reactor dependencies!
org.springframework.context.ApplicationContextException: Unable to
start reactive web server
Solved by annotating the dependency with #Lazy
I am new to spring. So I couldn't figure out what issue is there in the below code. I have two classes. I am defining a #Bean Channel and am autowiring that bean in the next class. I am using annotation for autowiring. When I try " System.out.println(externalChannel.toString());" am getting null values and the exception null pointer exception is thrown.
#Configuration
public class MessagingConfig
{
#Value("${service.name}")
private String queueName; // NOSONAR
#Value("${${user}")
private String schema;
#Value("${Owner}")
private String owner;
#Bean
public Channel externalChannel()
{
EventsProvider eventsProvider = new EventsProvider();
eventsProvider.setOwner(owner);
System.out.println("-------Cost And Events Channel-------"+eventsProvider.getEventsChannel());
return eventsProvider.getEventsChannel();
}
}
And Another class is
#Component
#LoggedService
#Monitored(useActualType = true)
public class MessagePublish {
#Autowired
private MessagingService messageService;
#Autowired
private Channel externalChannel;
public void publishTPSMessage(SourceTransaction sourceTransaction)
{
TPSEvent event = new TPSEvent(ContextHolder.getContextId(), new Date(), GuidUtils.generateGuid(),sourceTransaction);
Message<TPSEvent> message = new Message<TPSEvent>(event);
message.getHeader().setMessageType(TPSEvent.class.getName());
message.getHeader().setPayloadEncodingType(SystemCodecs.XML.name());
System.out.println(message.toString());
System.out.println(externalChannel.toString());
messageService.publish(externalChannel, message);
}
}
More Info
public Channel getEventsChannel() {
return Channel.builder()
.setName("necessarySources")
.setConnectionName("defaultConnection")
.setType(ChannelType.Topic)
.setConnectionData(AqSqlConnectionData.buildString(this.owner, "Safi"))
.setSubscriberNames(new String[]{"Safi_Autowire"})
.build();
}
Main Class
public class TPSHandler {
public static void main(String[] args) {
BatchExport batchExportBean=getBatchExportASJAXBElement();
System.out.println(" batchExportBean Trans Description : " + batchExportBean.getDueDate());
for(Pay pay :batchExportBean.getPay()) {
SourceTransaction sourceTransaction=mapPayBatchToSourceTransaction(pay,batchExportBean);
String sourceTraString = getSourceTransactionASXML(sourceTransaction);
System.out.println(" sourceTraString : \n" + sourceTraString);
MessagePublish messagePublish= new MessagePublish();
//SourceTransaction sourceTransaction= new SourceTransaction();
messagePublish.publishTPSMessage(sourceTransaction);
}
}
}
My Servlet.xml
<?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:jaxrs="http://cxf.apache.org/jaxrs"
xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://cxf.apache.org/jaxws
http://cxf.apache.org/schemas/jaxws.xsd
http://cxf.apache.org/jaxrs
http://cxf.apache.org/schemas/jaxrs.xsd">
<import resource="classpath:config-properties.xml" />
<import resource="classpath:datasource.xml" />
<import resource="classpath:transaction-manager.xml" />
<import resource="classpath:jmx.xml" />
<context:component-scan base-package="com.imosAdapter" />
<bean class="com.oasis.services.messaging.config.MessagingServicesConfig" />
<bean class="com.oasis.services.messaging.config.DefaultMessagingConnectorsConfig" />
<bean class="com.oasis.services.messaging.config.LoaderConfig" />
<context:annotation-config />
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>/config/oasis-component.properties</value>
</property>
</bean>
</beans>
The exception thrown:
Exception in thread "main" java.lang.NullPointerException
at com.imosAdapter.tps.events.MessagePublish.publishTPSMessage(MessagePublish.java:46)
at com.imosAdapter.tps.TPSHandler.main(TPSHandler.java:64)
What is the issue over here? Can anybody help me with this? what exactly I am missing here?
You need to initialize a Spring context at the start of your application when you do not create a servlet / run as a Server.
See Using Spring in a standalone application
I'm new to neo4j and spring in combination and spring at all. When I start debugging, I get the following exception:
Exception in thread "main"
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
bean named 'getSessionFactory' available
Can anyone help me please?
apllication-context.xml:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:neo4j="http://www.springframework.org/schema/data/neo4j"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/data/neo4j
http://www.springframework.org/schema/data/neo4j/spring-neo4j.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="de.unileipzig.analyzewikipedia.neo4j" />
<!--neo4j:config storeDirectory="C:/temp/neo4jdatabase" base-package="de.unileipzig.analyzewikipedia.neo4j.dataobjects"/-->
<neo4j:repositories base-package="de.unileipzig.analyzewikipedia.neo4j.repositories"/>
<tx:annotation-driven />
<bean id="graphDatabaseService" class="org.springframework.data.neo4j.support.GraphDatabaseServiceFactoryBean"
destroy-method="shutdown" scope="singleton">
<constructor-arg value="C:/develop/uni/analyze-wikipedia-netbeans/database"/>
<constructor-arg>
<map>
<entry key="allow_store_upgrade" value="true"/>
</map>
</constructor-arg>
</bean>
</beans>
Startup-Class
package de.unileipzig.analyzewikipedia.neo4j.console;
import de.unileipzig.analyzewikipedia.neo4j.dataobjects.Article;
import de.unileipzig.analyzewikipedia.neo4j.service.ArticleService;
import java.io.File;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Neo4JConsole {
/**
* MAIN: start the java file
*
* #param args as string array
*/
public static void main(String[] args) {
String cwd = (new File(".")).getAbsolutePath();
ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
ArticleService service = (ArticleService) context.getBean("articleService");
Article art = createArticle();
createArticle(service, art);
System.out.println("Article created");
}
private static Article createArticle() {
Article article = new Article();
article.setTitle("Title");
return article;
}
private static Article createArticle(ArticleService service, Article art) {
return service.create(art);
}
}
Thank you.
Do you have this configuration?
#Configuration
#EnableNeo4jRepositories("org.neo4j.cineasts.repository")
#EnableTransactionManagement
#ComponentScan("org.neo4j.cineasts")
public class PersistenceContext extends Neo4jConfiguration {
#Override
public SessionFactory getSessionFactory() {
return new SessionFactory("org.neo4j.cineasts.domain");
}
}
For more information, try to look here
I have a message factory bean configured as shown 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:ws="http://www.springframework.org/schema/web-services"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/web-services
http://www.springframework.org/schema/web-services/web-services-2.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="soapMessageFactory" class="javax.xml.soap.MessageFactory" factory-method="newInstance" />
<bean id="saajMessageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory">
<constructor-arg ref="soapMessageFactory" />
</bean>
<bean id="myService" class="com.mypackage.TestEndPoint">
<property name="saajMessageFactory" ref="saajMessageFactory" />
</bean>
</beans>
The TestEndpoint class looks like this
#Endpoint
public class TestEndPoint {
ObjectFactory objectFactory = new ObjectFactory();
SaajSoapMessageFactory saajMessageFactory;
#PayloadRoot(namespace="http://ws.mypackage.com", localPart="downloadSaajMessageRequest")
#ResponsePayload
public JAXBElement<DownloadResponseSaajType> invoke(#RequestPayload DownloadSaajMessageRequest req, MessageContext context ) throws Exception {
DownloadResponseSaajType response = new DownloadResponseSaajType();
//DownloadResponseSaajType.PayLoad payload = new DownloadResponseSaajType.PayLoad();
DataHandler handler = new javax.activation.DataHandler(new FileDataSource("c:\\temp\\maven-feather.png"));
SaajSoapMessage message = saajMessageFactory.createWebServiceMessage();
message.addAttachment("picture", handler);
message.addAttachment("picture", handler);
//payload.setMessagePayLoad(handler);
//response.setPayLoad(payload);
response.setRequestName("NAMEOF");
context.setResponse(message);
return objectFactory.createDownloadSaajMessageResponse(response);
}
public void setSaajMessageFactory(SaajSoapMessageFactory saajMessageFactory){
this.saajMessageFactory = saajMessageFactory;
}
public SaajSoapMessageFactory getSaajMessageFactory(){
return saajMessageFactory;
}
}
I am having a few problems trying to get the endpoint to work and when i tried to debug the code i found that saajMessageFactory is never initialised and it is always null. Have i done something wrong with the configuration?
You have to add PayloadRootAnnotationMethodEndpointMapping bean to your configuration xml.
<bean class="org.springframework.ws.server.endpoint.mapping.PayloadRootAnnotationMethodEndpointMapping"/>
I have weird situation.
I tried to create new bean while using the #Configuration an #Bean this way:
package com.spring.beans.ParkingCar;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
public class CarMaker
{
#Bean
public CarBean createNewCar()
{
CarBean carBean=new CarBean();
return carBean;
}
}
package com.spring.beans.ParkingCar;
import org.apache.log4j.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
public class CarBean
{
private int x = 3;
static Logger logger = Logger.getLogger(CarBean.class);
public void driveCar()
{
logger.debug("I am driving my car" + x);
}
}
and then my test class looks like this:
public static void execute()
{
try
{
PropertyConfigurator.configure("log4j.properties");
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
CarMaker carMaker = (CarMaker) context.getBean("carMaker");
CarBean carBean = carMaker.createNewCar();
carBean.driveCar();
}
catch (Throwable e)
{
logger.error(e);
}
}
my applicationContext.xml looks like this:
<?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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" 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/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!-- Must for auto wiring
<context:annotation-config />
-->
<context:component-scan
base-package="com.spring.beans.ParkingCar">
</context:component-scan>
<aop:aspectj-autoproxy />
<bean id="Spring3HelloWorldBean" class="com.spring.aspect.Spring3HelloWorld">
<property name="myname" value="idan" />
</bean>
<bean id="SecurityAspect" class="com.spring.aspect.SecurityAspect">
</bean>
<bean id="CalculateStrategyBean" class="com.spring.beans.calculator.CalculateStrategyBean">
<constructor-arg value="plus" />
</bean>
<bean id="CalculatorBean" class="com.spring.beans.calculator.CalculatorBean">
<constructor-arg ref="CalculateStrategyBean" />
<constructor-arg ref="CalculateNumbersHolderBean" />
</bean>
<bean id="CalculateNumbersHolderBean" class="com.spring.beans.calculator.CalculateNumbersHolderBean">
<constructor-arg value="10" />
<constructor-arg value="20" />
</bean>
<bean id="lisenceDrive" class="com.spring.beans.ParkingCar.LisenceDrive"
p:carLisenceNum="333" p:isValidateCar="true" />
<bean id="AmbulancelisenceDrive" class="com.spring.beans.ParkingCar.LisenceDrive"
p:carLisenceNum="999" p:isValidateCar="false" />
<bean id="TransitlisenceDrive" class="com.spring.beans.ParkingCar.LisenceDrive"
p:carLisenceNum="111" p:isValidateCar="false" />
<bean id="TransitVechileDetails" class="com.spring.beans.ParkingCar.VechileDetails"
p:modelName="Transit-AS" p:numOfWheels="4" p:year="1992" />
<!-- Wiring without annotations-->
<!--
<bean id="Ambulance"
class="com.spring.beans.ParkingCar.FourWheelsVechile"
p:modelName="GMC" p:numOfWheels="4" p:year="1997"
p:lisenceDrive-ref="AmbulancelisenceDrive" /> <bean id="Bike"
class="com.spring.beans.ParkingCar.TwoWheelsVechile" autowire="byName"
p:modelName="T-BIRD" p:numOfWheels="2" p:year="2012" /> <bean
id="Transit" class="com.spring.beans.ParkingCar.FourWheelsVechile"
p:lisenceDrive-ref="TransitlisenceDrive" autowire="constructor">
-->
<bean id="Ambulance" class="com.spring.beans.ParkingCar.FourWheelsVechile"
p:modelName="GMC" p:numOfWheels="4" p:year="1997" p:lisenceDrive-ref="AmbulancelisenceDrive" />
<!-- Wiring with annotations
<bean id="Bike" class="com.spring.beans.ParkingCar.TwoWheelsVechile"
autowire="byName" p:modelName="T-BIRD" p:numOfWheels="2" p:year="2012" />
<bean id="Transit" class="com.spring.beans.ParkingCar.FourWheelsVechile"
p:lisenceDrive-ref="TransitlisenceDrive">
</bean>
-->
</beans>
Now when I ran it on MyEclipse thru main it worked just fine. but when I uploaded it to my stand alone application which is running on Linux I got:
2012-07-01 14:11:21,152 com.spring.test.Spring3HelloWorldTest [ERROR] org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'carMaker' is defined
Any idea why it didn't work there?
Thanks.
#Configuration indicates that a class declares one or more #Bean methods while #Bean creates a new bean which have same name as the name of the method annotated with #Bean .
In your code sample bean with name createNewCar will be created as method createNewCar() method is annotated by #Bean.
Try this
CarBean carBean = (CarBean) context.getBean("createNewCar");
carBean.driveCar();
Few things to look at
Why to annotate class CarBean as #Configuration? It dont contain any bean defination ie. method with #Bean annotation.
Why to invoke createNewCar() method as it is already annotated with #Bean? (Let Spring do its work)
Check this link it will help you to get familiar with #Configuration and #Bean annotation.