Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a Java bean? [duplicate]

Tags:

java

javabeans

Possible Duplicate:
What's the point of beans?

What is a javabean? What is it used for? And what are some code examples? I heard it is used for something to do with getter and setter methods? I'm quite confused about what a java bean is and where you even access it. I googled it but couldn't find a definite answer.

like image 301
Daniel Gleason Avatar asked Jul 10 '12 05:07

Daniel Gleason


People also ask

Can two beans have same name?

Spring beans are identified by their names within an ApplicationContext. Therefore, bean overriding is a default behavior that happens when we define a bean within an ApplicationContext that has the same name as another bean. It works by simply replacing the former bean in case of a name conflict.

Can two beans make the same instance?

Spring will create two instances in this scenario. Spring container creates a singleton instance per bean definition. When you call getContext. getBean("myBean") will always give you same instance for myBean bean definition.

Can we use @qualifier and @bean together?

NOTE: if you are creating bean with @Bean, it will be injected byType if there is duplicates then it will injected byName. we no need to mention @Bean(name="bmwDriver") . so you can directly use qualifier("bmwDriver") wherever you need in classes.

Can we configure two beans of the same class with the different ID in spring?

It will throw an error at runtime, as you can not define two Sspring beans of the same class with Singleton Scope in XML. (Very rare) The reference check will return true, as the container maintains one object. Both bean definitions will return the same object, so the memory location would be the same.


1 Answers

Java Bean is a normal Java class which has private properties with its public getter and setter method.

Java Beans are generally used as helper class.

Example -

public class User implements java.io.Serializable {      private String name;     private Integer age;      public String getName(){         return this.name;     }      public void setName(String name){         this.name = name;     }      public Integer getAge(){         return this.age;     }      public void setAge(Integer age){         this.age = age;     } } 

Implementing Serializable is not mandatory but is very useful if you'd like to persist or transfer Javabeans outside Java's memory, e.g. in harddisk or over network.

Places where JavaBeans are used?

like image 67
Pramod Kumar Avatar answered Sep 22 '22 21:09

Pramod Kumar