Getting NoSuchBeanDefinitionException while Referencing JavaConfig in XML configuration - java

I am beginner in Spring and trying to learn different ways of configuring Spring beans using XML and Java Config classses. In below demo program, i have configured EmployeeService and EmployeeDAO beans in Java Config classes and Employee bean in XML file. And then i am trying to Reference JavaConfig in XML configuration and use this XML configuration file in Main Class to get the Employee Service bean. I am getting NoSuchBeanDefinitionException while executing the below program. Can someone please help me to understand what is wrong here.
DAOConfig.java
package com.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.demo.dao.EmployeeDAO;
#Configuration
public class DAOConfig {
#Bean
public EmployeeDAO getEmployeeDAO(){
return new EmployeeDAO();
}
}
ServiceConfig.java
package com.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.demo.dao.EmployeeDAO;
import com.demo.service.EmployeeService;
#Configuration
public class ServiceConfig {
#Bean(name="myEmployeeService")
public EmployeeService getEmployeeService(EmployeeDAO empDAO){
EmployeeService empService = new EmployeeService();
empService.setEmpDAO(empDAO);
return empService;
}
}
MainConfig.java
package com.demo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
#Configuration
#Import({ DAOConfig.class, ServiceConfig.class })
public class MainConfig {
}
EmployeeService.java:
package com.demo.service;
import com.demo.dao.EmployeeDAO;
public class EmployeeService {
private EmployeeDAO empDAO;
public void setEmpDAO(EmployeeDAO empDAO) {
this.empDAO = empDAO;
}
public void insertEmployee() {
System.out.println("insertEmployee called..");
empDAO.insertEmployeeDetails();
}
public void updateEmployee() {
System.out.println("updateEmployee called..");
empDAO.updateEmployeeDetails();
}
public void deleteEmployee() {
System.out.println("deleteEmployee called..");
empDAO.deleteEmployeeDetails();
}
}
EmployeeDAO.java
package com.demo.dao;
public class EmployeeDAO {
public void insertEmployeeDetails(){
System.out.println("insertEmployeeDetails called..");
}
public void updateEmployeeDetails(){
System.out.println("updateEmployeeDetails called..");
}
public void deleteEmployeeDetails(){
System.out.println("deleteEmployeeDetails called..");
}
}
Employee.java:
package com.demo.dto;
public class Employee {
private String name;
private String id;
private String salary;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSalary() {
return salary;
}
public void setSalary(String salary) {
this.salary = salary;
}
#Override
public String toString() {
return "Employee [name=" + name + ", id=" + id + ", salary=" + salary + "]";
}
}
mixAppContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean class="com.demo.config.MainConfig" />
<bean id="employeeObj" class="com.demo.dto.Employee">
<property name="name" value="ABC"></property>
<property name="id" value="123"></property>
<property name="salary" value="10000"></property>
</bean>
</beans>
JavaConfigInXmlMixDemo.java:
package com.demo.main;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.demo.dto.Employee;
import com.demo.service.EmployeeService;
public class JavaConfigInXmlMixDemo {
public static void main(String args[]){
//ApplicationContext context = new AnnotationConfigApplicationContext(MainConfig.class);
ApplicationContext context = new ClassPathXmlApplicationContext("mixAppContext.xml");
EmployeeService service = (EmployeeService) context.getBean("myEmployeeService");
Employee employee = (Employee) context.getBean("employeeObj");
service.insertEmployee();
service.updateEmployee();
service.deleteEmployee();
System.out.println(employee);
}
}
I am getting below exception:
Exception:
INFO: Loading XML bean definitions from class path resource [mixAppContext.xml]
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'myEmployeeService' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:701)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1180)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:284)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1076)
at com.demo.main.JavaConfigInXmlMixDemo.main(JavaConfigInXmlMixDemo.java:15)

Like described here you need include <context:annotation-config /> in your xml. Without this tag spring will ignore all annotation and create instance of your configuration bean as it's a simple bean.

Related

Error in fetching table through JpaRepository

I am trying to fetch data from a table in MySQL using JpaRepository.
I am geeting an error by running code like -
Error creating bean with name 'chassiscontroller': Unsatisfied dependency expressed through field 'service': Error creating bean with name 'chassisserviceimpl': Unsatisfied dependency expressed through field 'dao': Error creating bean with name 'chassisdao' defined in com.ChassisInfo.chassis.dao.chassisdao defined in #EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Not a managed type: class com.ChassisInfo.model.chassismodel.
Controller
package com.ChassisInfo.chassis.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ChassisInfo.chassis.model.ChassisModel;
import com.ChassisInfo.chassis.service.ChassisService;
#RestController
public class ChassisController {
#Autowired
private ChassisService service;
#GetMapping("/chnum")
public List<ChassisModel> getchassisnumberinfo(){
return service.getAll();
}
}
Service-
package com.ChassisInfo.chassis.service;
import java.util.List;
import com.ChassisInfo.chassis.model.ChassisModel;
public interface ChassisService{
List<ChassisModel> getAll();
}
ServiceImpl-
package com.ChassisInfo.chassis.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ChassisInfo.chassis.dao.ChassisDao;
import com.ChassisInfo.chassis.model.ChassisModel;
#Service
#lombok.AllArgsConstructor
#lombok.NoArgsConstructor
public class ChassisServiceimpl implements ChassisService {
#Autowired
private ChassisDao dao;
#Override
public List<ChassisModel> getAll() {
// TODO Auto-generated method stub
return dao.findAll();
}
Dao-
package com.ChassisInfo.chassis.dao;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.stereotype.Repository;
import com.ChassisInfo.chassis.model.ChassisModel;
#Repository
#EnableJpaRepositories
public interface ChassisDao extends JpaRepository<ChassisModel,String> {
#Query(value = "Select * from chassis_master" ,nativeQuery = true)
List<ChassisModel> findAll();
}
Model-
package com.ChassisInfo.model;
public class chassismodel {
private String vin;
private String active;
private String chassisNumber;
private String chassisSeries;
private String statusChangedTime;
private String tag;
private String truckid;
private String id;
private String chassis_number;
private String chassis_series;
private String status_changed_time;
private String truck_id;
public String getVin() {
return vin;
}
public void setVin(String vin) {
this.vin = vin;
}
public String getActive() {
return active;
}
public void setActive(String active) {
this.active = active;
}
public String getChassisSeries() {
return chassisSeries;
}
public void setChassisSeries(String chassisSeries) {
this.chassisSeries = chassisSeries;
}
public String getStatusChangedTime() {
return statusChangedTime;
}
public void setStatusChangedTime(String statusChangedTime) {
this.statusChangedTime = statusChangedTime;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public String getTruckid() {
return truckid;
}
public void setTruckid(String truckid) {
this.truckid = truckid;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getChassis_number() {
return chassis_number;
}
public void setChassis_number(String chassis_number) {
this.chassis_number = chassis_number;
}
public String getChassis_series() {
return chassis_series;
}
public void setChassis_series(String chassis_series) {
this.chassis_series = chassis_series;
}
public String getStatus_changed_time() {
return status_changed_time;
}
public void setStatus_changed_time(String status_changed_time) {
this.status_changed_time = status_changed_time;
}
public String getTruck_id() {
return truck_id;
}
public void setTruck_id(String truck_id) {
this.truck_id = truck_id;
}
public String getChassisNumber() {
return chassisNumber;
}
public void setChassisNumber(String chassisNumber) {
this.chassisNumber = chassisNumber;
}
}
ChassisApplication-
package com.ChassisInfo.chassis;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import com.ChassisInfo.chassis.controller.ChassisController;
#SpringBootApplication
#EnableJpaRepositories
public class ChassisApplication {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(ChassisApplication.class, args);
ChassisController chassisController = context.getBean(ChassisController.class);
chassisController.getchassisnumberinfo();
}
}
Try to use #RequiredArgsConstructor (lombok) in chassisserviceimpl, since dao field is not accessible for autowiring. Also add final for the field:
private final chassisdao dao;
This is probably because you are missing the #EnableJpaRepositories(basePackages = "your.package.name") in you #SpringBootApplication
This is the Annotation to enable JPA repositories. Will scan the package of the annotated configuration class for Spring Data repositories by default.

Error creating bean with name 'readstrackerDataLoaderApplication': Unsatisfied dependency expressed through field 'authorRepository'

I know that this question is a duplicate, but I have tried many of the suggestions that I found with no effect.
I am a beginner to spring boot, and I am following a tutorial using Spring boot and Cassandra. I get this error once SpringApplication.run(ReadstrackerDataLoaderApplication.class, args) is executed.
ReadstrackerDataLoaderApplication.java
package com.readstracker.demo;
#SpringBootApplication(scanBasePackages = {"com.readstracker.repositories", "com.readstracker.entities"})
//#ComponentScan("repositories.AuthorRepository")
#EnableConfigurationProperties(DataStaxAstraProperties.class)
#EnableCassandraRepositories("com.readstracker.repositories")
#ComponentScan("com.readstracker.entities")
#Service
public class ReadstrackerDataLoaderApplication {
#Autowired
private AuthorRepository authorRepository;
public static void main(String[] args) {
SpringApplication.run(ReadstrackerDataLoaderApplication.class, args);
}
#PostConstruct
public void start() {
Author author = new Author();
author.setId("id");
author.setName("name");
author.setPersonalName("personalName");
authorRepository.save(author);
}
#Bean
public CqlSessionBuilderCustomizer sessionBuilderCustomizer(DataStaxAstraProperties astraProperties) {
Path bundle = astraProperties.getSecureConnectBundle().toPath();
return builder -> builder.withCloudSecureConnectBundle(bundle);
}
}
AuthorRepository.java
package com.readstracker.repositories;
import org.springframework.data.cassandra.repository.CassandraRepository;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import com.readstracker.entities.Author;
#Repository
public interface AuthorRepository extends CassandraRepository<Author, String> {
}
Author.java
package com.readstracker.entities;
import org.springframework.data.annotation.Id;
import org.springframework.data.cassandra.core.cql.PrimaryKeyType;
import org.springframework.data.cassandra.core.mapping.CassandraType;
import org.springframework.data.cassandra.core.mapping.CassandraType.Name;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.data.cassandra.core.mapping.Column;
import org.springframework.data.cassandra.core.mapping.PrimaryKeyColumn;
import org.springframework.data.cassandra.core.mapping.Table;
#Table(value = "author_by_id")
#Component
public class Author {
#Id
#PrimaryKeyColumn(name = "author_id", ordinal = 0, type = PrimaryKeyType.PARTITIONED)
private String id;
#Column("author_name")
#CassandraType(type = Name.TEXT)
private String name;
#Column("personal_name")
#CassandraType(type = Name.TEXT)
private String personalName;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPersonalName() {
return personalName;
}
public void setPersonalName(String personalName) {
this.personalName = personalName;
}
}
Here is my project directory

OpenJPA & Spring Boot 2 & Gradle

I'm trying to run OpenJPA with newest Spring Boot 2 and Gradle.
The problem is that Spring 5 does not support OpenJPA anymore.
When I run the application I see an error:
Caused by: org.apache.openjpa.persistence.ArgumentException: This configuration disallows runtime optimization, but the following listed types were not enhanced at build time or at class load time with a javaagent: "
aero.onair.accground.aft.TestEntity".
There was some plugin for older Gradle which was doing the entity enhancement with the use of openjpa library, but it does not work with the newer.
I have used an adapter and dialect like in this repo:
https://github.com/apache/syncope/tree/master/core/persistence-jpa/src/main/java/org/springframework/orm/jpa/vendor
I have the persistence.xml file in resources/jpa/persistence.xml
I have also tried to move it to resources/META-INF/
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
version="2.0">
<persistence-unit name="aftDbUnitName">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<class>aero.onair.accground.aft.TestEntity</class>
</persistence-unit>
</persistence>
My configuration for OpenJPA:
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.apache.openjpa.persistence.PersistenceProviderImpl;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.autoconfigure.transaction.TransactionManagerCustomizers;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.AbstractJpaVendorAdapter;
import org.springframework.transaction.jta.JtaTransactionManager;
#Configuration
public class OpenJpaConfig extends JpaBaseConfiguration {
protected OpenJpaConfig(DataSource dataSource,
JpaProperties properties,
ObjectProvider<JtaTransactionManager> jtaTransactionManager,
ObjectProvider<TransactionManagerCustomizers> transactionManagerCustomizers) {
super(dataSource, properties, jtaTransactionManager, transactionManagerCustomizers);
}
#Override
protected AbstractJpaVendorAdapter createJpaVendorAdapter() {
OpenJpaVendorAdapter jpaVendorAdapter = new OpenJpaVendorAdapter();
jpaVendorAdapter.setShowSql(true);
return jpaVendorAdapter;
}
#Override
protected Map<String, Object> getVendorProperties() {
return new HashMap<>(0);
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setDataSource(getDataSource());
factory.setPersistenceProviderClass(PersistenceProviderImpl.class);
factory.setJpaVendorAdapter(new OpenJpaVendorAdapter());
factory.setPersistenceXmlLocation("jpa/persistence.xml");
return factory;
}
}
Test Entity:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class TestEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And finally the main Application class:
#SpringBootApplication(exclude = {XADataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
#Slf4j
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Autowired
TestEntitiyRepository testEntitiyRepository;
#PostConstruct
public void test() {
long count = testEntitiyRepository.count();
log.info("Count = {}", count);
TestEntity entitiy = new TestEntity();
entitiy.setName("testtttt");
testEntitiyRepository.save(entitiy);
count = testEntitiyRepository.count();
log.info("Count after save = {}", count);
}
}
The best solution for me was to add a plugin from this page:
https://github.com/radcortez/openjpa-gradle-plugin
Another solution is to set a javaagent in VM options:
-javaagent:/path/openjpa-all-3.1.0.jar

Class not found exception netbeans spring mvc

Error:
Caused by: java.lang.ClassNotFoundException: WebApplication1.SourcePackages.Domain.UserService
Here is part of the the dispatcher-servlet.xml code
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
<bean id="UserService" class="WebApplication1.SourcePackages.Domain.UserService" />
<context:component-scan base-package="WebApplication1.SourcePackages.Controller" />
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
And here are screenshot of the files:
UserController
package Controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import Service.UserService;
import Domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
#RequestMapping("/userRegistration.htm")
#SessionAttributes("user")
public class UserController {
private UserService userService;
#Autowired
public void setUserService(UserService userService) {
this.userService = userService;
}
#RequestMapping(method = RequestMethod.GET)
public String showUserForm(ModelMap model)
{
User user = new User();
model.addAttribute(user);
return "userForm";
}
#RequestMapping(method = RequestMethod.POST)
public String onSubmit(#ModelAttribute("user") User user) {
userService.add(user);
return "UserSuccess";
}
}
User.java
package Domain;
/**
*
* #author fiona
*/
public class User {
private String name;
private String password;
private String gender;
private String country;
private String aboutYou;
private String[] community;
private Boolean mailingList;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getAboutYou() {
return aboutYou;
}
public void setAboutYou(String aboutYou) {
this.aboutYou = aboutYou;
}
public String[] getCommunity() {
return community;
}
public void setCommunity(String[] community) {
this.community = community;
}
public Boolean getMailingList() {
return mailingList;
}
public void setMailingList(Boolean mailingList) {
this.mailingList = mailingList;
}
}
UserService.java
package Service;
import Domain.User;
public class UserService {
public void add(User user) {
//Persist the user object here.
System.out.println("User added successfully");
}
}
This is occurring because you have included the folder structure "WebApplication1.SourcePackages" in the class name for the bean and in the package name for component scan.
It is not a package name. "WebApplication1" is the name of the NetBeans project. "SourcePackages" is the name of the structure which contains all Java packages and classes for the project.
In your Spring config file, you just need to provide the fully qualified class name which is the package name for the class followed by the class name.
Sample provided below
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
<bean id="userService" class="Service.UserService" />
<context:component-scan base-package="Controller" />
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />

What is the advantage of #Autowired annotaion?

In my spring example ,I declared two beans with following XML configuration file.
EmployeeBean.java
package autowire;
import org.springframework.beans.factory.annotation.Autowired;
public class EmployeeBean {
private String fullName;
#Autowired
private DepartmentBean departmentBean;
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public DepartmentBean getDepartmentBean() {
return departmentBean;
}
}
DepartmentBean.java
package autowire;
public class DepartmentBean {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
spring-servlet.xml
<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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<context:annotation-config />
<bean id="employee" class="autowire.EmployeeBean" autowire="byType">
<property name="fullName" value="Charith"></property>
</bean>
<bean id="deptment" class="autowire.DepartmentBean">
<property name="name" value="IT Department"></property>
</bean>
</beans>
TestAutowire .java
package autowire;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestAutowire {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"spring-servlet.xml"});
EmployeeBean employee = (EmployeeBean)context.getBean("employee");
System.out.println(employee.getFullName());
System.out.println(employee.getDepartmentBean().getName());
}
}
Above example is woking fine.After that I removed '#Autowired' annotation and add following lines to EmployeeBean.java
public void setDepartmentBean(DepartmentBean departmentBean) {
this.departmentBean = departmentBean;
}
Now the example working fine with same output.My question is , What is the actual benefit when used '#Autowired' annotation?Because the code working fine without annotation but with setter method also.Pls help me.
#AutoWired can be useful as it saves you time writing "wiring" code. You don't have to call somewhere in your code the setDepartment method to init your object. Spring will do it for you.
In your case, see below how to accomplish this using annotations only. Note the use of #Component annotation for indicating auto scan components to Spring. Also note that no XML file is now needed.
EmployeeBean.java
package autowire;
/* Imports go here ... */
#Component
public class EmployeeBean {
private String fullName;
#Autowired
private DepartmentBean departmentBean;
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public DepartmentBean getDepartmentBean() {
return departmentBean;
}
}
DepartmentBean.java
package autowire;
/* Imports go here ... */
#Component
public class DepartmentBean {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
TestAutowire .java
package autowire;
/* Imports go here ... */
public class TestAutowire {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext();
context.scan("autowire");
context.refresh();
EmployeeBean employee = (EmployeeBean)context.getBean("employee");
System.out.println(employee.getFullName());
System.out.println(employee.getDepartmentBean().getName());
}
}
References:
Spring 3.2.x: Java Based container configuration

Categories

Resources