18
Jul
Create Bean in Constructor Based with Annotations
Create Bean in Constructor Based with Annotations
Step 1: Create Student.java in entitites package
=================================================
package entities;
public class Student {
private String id, name;
private int age;
private double score;
public String getId() {
return id;
}
public Student(){
}
public Student(String id, String name, int age, double score){
this.id = id;
this.name = name;
this.age = age;
this.score = score;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
}
Step 2: Configuration file:
=============================
package annotations;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import entities.Student;
@Configuration
public class StudentConfigConst {
@Bean(name = "student1")
public Student student1() {
return new Student("st01", "student name", 24, 7.6);
}
}
Step 3: Client application
===========================
package entities;
import entities.Student;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import annotations.StudentConfigConst;
public class MainConstructorAnnotations {
public static void main(String[] args) {
try {
AbstractApplicationContext context = new AnnotationConfigApplicationContext(StudentConfigConst.class);
Student student1 = (Student) context.getBean("student1");
System.out.println("Student data from beans ");
System.out.println("Id " + student1.getId());
System.out.println("Name" + student1.getName());
System.out.println("Age " + student1.getAge());
System.out.println("Score" + student1.getScore());
context.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
output:
=========
Student data from beans
Id st01
Namestudent name
Age 24
Score7.6
0 comments