250+ TOP MCQs on Creating Beans and Answers

Java Spring Multiple Choice Questions & Answers (MCQs) on “Creating Beans”.

1. Beans can be created by which of the following properties?
a) Scope
b) Property
c) Class
d) It’s own constructor
Answer: d
Clarification: Class’s constructor can create bean.

2. Which attribute is used to specify class name of the bean?
a) name
b) id
c) class
d) constructor-args
Answer: c
Clarification: Class attribute is mandatory and denotes the class used to create bean.

3. Which of the following method can be used to used to instantiate a method?
a) static factory method
b) default-init method
c) destroy method
d) lazy-init method
Answer: a
Clarification: Class attribute is used to specify the name of the class that contains the static factory method.

4. Which attribute is used to specify static factory-method?
a) factory-method
b) default-init method
c) destroy method
d) lazy-init method
Answer: a
Clarification: factory-method attribute denotes the name of actual method of the class.

5. Purpose of Static Factory Method?
a) Static method to create an object
b) Initialize bean
c) All of the mentioned
d) None of the mentioned
Answer: a
Clarification: Instantiate a bean using static method.

6. Exception thrown by factory method?
a) IllegalArgumentException
b) IndexOutofBoundException
c) ClassPathNotFoundException
d) BeanCreationException
Answer: d
Clarification: Spring generates the above mentioned exception, in case something’s wrong.

7. What will be the output?
Snippet of Code:

public class CreatePro {
    String ProductId;
    public CreatePro(String ProductId)	{
        this.ProductId = ProductId;
    }
 
public static Product creation_Product(String productId) {	
    System.out.println("Bean Created");
    if ("aaa".equals(productId)) {
        return new Battery("AAA", 2.5);
    } else if ("cdrw".equals(productId)) {
        return new Disc("CD-RW", 1.5);
    }
}
}
<beans ...>
<bean id="aaa" class="CreatePro"
    factory-method="createProduct">
    <constructor-arg value="aaa" />
bean>
<bean id="cdrw" class="CreatePro"
    factory-method="createProduct">
    <constructor-arg value="cdrw" />
bean>
beans>

a) BeanCreationException
b) Bean Created
c) ClassPathException
d) None of the mentioned
Answer: a
Clarification: Since factory-method doesn’t exists in the ProductCreator class, so exception thrown.
Output: BeanCreationException

8. A bean can have more than one name using multiple id attributes?
a) True
b) False
Answer: a
Clarification: Beans are allowed to have more than one ids.

9. Bean’s naming convention:-
starts with lowercase, camelcase from then on.?
a) True
b) False
Answer: a
Clarification: Beans follow naming conventions.

10. Beans can be created by which of the following properties?
a) Static factory-method
b) Instance Factory-Method
c) All of the mentioned
d) None of the mentioned
Answer: c
Clarification: Instantiate a bean via static and instance Factory methods.

11. The bean instance is mentioned by the factory-method attribute, while the factory method is signified by the factory-bean attribute?
a) True
b) False
Answer: b
Clarification: The bean instance is mentioned by factory-bean attr while factory method is for factory-method attr.

12. One factory class can also hold more than one factory method True/False?
a) True
b) False
Answer: a
Clarification: A single instantiated bean can have more than one methods.

13. Snippet of Code:

public class CreatePro 
{
     String ProductId;
     public CreatePro(String ProductId)	
     this.ProductId = ProductId;
}
 
public static Product creation_Product(String productId) 
{	
     System.out.println("Bean Created");
     if ("aaa".equals(productId)) 
     {
        return new Battery("AAA", 2.5);
     } 
     else if ("cdrw".equals(productId)) 
     {
	return new Disc("CD-RW", 1.5);
     }
 
}
 
  <beans ...>
	<bean id="aaa" class="CreatePro"
	factory-method="createProduct">
	<constructor-arg value="aaa" />
	bean>
	<bean id="cdrw" class="CreatePro"
	factory-method="createProduct">
	<constructor-arg value="cdrw" />
	bean>
  beans>
  slight change in XML file:-
 
<bean id="aaa" factory-bean="productCreator"
factory-method="createProduct">
<constructor-arg value="aaa" />
bean>
<bean id="cdrw" factory-bean="productCreator"
factory-method="createProduct">
<constructor-arg value="cdrw" />
bean>

What will be the output:-
a) BeanCreationException
b) IllegalArgumentException
c) New Product will be created
d) None of the mentioned
Answer: c
Clarification: Factory-Bean is used instead of class.

14. Instance Factory method main purpose is to encapsulate the object-creation process in a method of another object instance.
a) True
b) False
Answer: a
Clarification: The client who requests an object can simply make a call to this method without knowing about the creation detail.

15. Which Attribute is used to specify the bean declared?
a) factory-bean
b) scope
c) getBean
d) declareBean
Answer: a
Clarification: To declare a bean created by an instance factory method, you specify the bean hosting the factory method in the factory-bean attribute.

250+ TOP MCQs on Securing and persisting objects in Web Flows and Answers

Java Spring Multiple Choice Questions & Answers (MCQs) on “Securing and persisting objects in Web Flows”.

1. Element which secures web flows.
a) secured
b) security
c) sec
d) none of the mentioned
Answer: a
Clarification: With Spring Security configured properly, you can simply secure a flow, a state, or a transition by embedding the secured element with required access attributes specified.

2. To secure web flows with Spring Security.
a) DelegatingFilter
b) DelegatingFilterProxy
c) DelegatingProxy
d) None of the mentioned
Answer: b
Clarification: To secure web flows with Spring Security, you first have to configure a DelegatingFilterProxy filter in the web deployment descriptor (i.e., web.xml).

3. Group id to add spring security using Maven.

<dependency>
   <groupId>groupId>
   <artifactId>spring-security-coreartifactId>
   <version>3.0.2.RELEASEversion>
dependency>

a) org.springframework.secure
b) org.springframework.security
c) org.springframework.securedflow
d) none of the mentioned
Answer: b
Clarification: org.springframework.secur is used to secure web flows with Spring Security.

4. auto-config provides only default form-based login service.
a) True
b) False
Answer: b
Clarification: HTTP auto-config, which provides a default form-based login service, an anonymous login service, and so on.

5. To enable Spring security for web flows.
a) SecurityFlowExecutionListener
b) SecurityFlowExecution
c) FlowSecurity
d) SecurityFlowListener
Answer: a
Clarification: You have to register the flow execution listener SecurityFlowExecutionListener in the flow executor to enable Spring Security for web flow.

6. Which of the following class should replace ‘?’.

<beans ...>
...
  <webflow:flow-executor id="flowExecutor">
  <webflow:flow-execution-listeners>
  <webflow:listener ref="securityFlowExecutionListener" />
  webflow:flow-execution-listeners>
  webflow:flow-executor>
  <bean id="securityFlowExecutionListener" class="?" />
beans>

a) org.springframework.webflow.security.SecurityFlow
b) org.springframework.webflow.SecurityFlowExecutionListener
c) org.springframework.webflow.security.SecurityFlowExecutionListener
d) org.springframework.security.SecurityFlowExecutionListener
Answer: c
Clarification: You have to register the flow execution listener SecurityFlowExecutionListener in the flow executor to enable Spring Security for web flow.

7. Which attribute is used to access security element of web flow.
a) attribute
b) attributes-security
c) attributes
d) none of the mentioned
Answer: c
Clarification: You can specify multiple access attributes required for accessing this web flow in the attributes attribute, separated by commas.

8. Spring web flow supports integration with.
a) JSF
b) Hibernate
c) JPA
d) All of the mentioned
Answer: d
Clarification: Spring Web Flow 2.0 comes with support for JPA and Hibernate.

9. To integrate JPA with Spring Web flows.
a) JpaFlowExecutionListener
b) HibernateFlowExecutionListener
c) All of the mentioned
d) None of the mentioned
Answer: a
Clarification: To have Spring Web Flow manage the persistence contexts for your web flows, you have to register a flow execution listener (e.g., JpaFlowExecutionListener for JPA.

10. To integrate Hibernate with Spring Web flows.
a) JpaFlowExecutionListener
b) HibernateFlowExecutionListener
c) All of the mentioned
d) None of the mentioned
Answer: b
Clarification: To have Spring Web Flow manage the persistence contexts for your web flows, you have to register a flow execution listener (e.g., HibernateFlowExecutionListener for Hibernate.

11. HibernateFlowExecutionListener and JpaFlowExecutionListener both belongs to which of the package.
a) org.springframework.web.persistence package
b) org.springframework.persistence package
c) org.springframework.webflow package package
d) org.springframework.webflow.persistence package
Answer: d
Clarification: JpaFlowExecutionListener for JPA and HibernateFlowExecutionListener for Hibernate, both of which belong to the org.springframework.webflow.persistence package) in the flow executor.

12. JpaFlowExecutionListener and Hibernate Listener binds to flow scope.
a) True
b) False
Answer: a
Clarification: . When a new flow starts, this listener creates a new persistence context (e.g., a JPA entity manager or a Hibernate session) and binds it to the flow scope.

13. Libraries used to integrate Hibernate with JPA.
a) Hibernate 3
b) Hibernate 3 Entity Manager
c) JPA API
d) All of the mentioned
Answer: d
Clarification: To use Hibernate as the JPA engine, you have to add Hibernate 3, the Hibernate 3 EntityManager, the JPA API, and ehcache.

14. To configure JPA vendor-specific information.
a) JPA vendor adaptor
b) Data source
c) All of the mentioned
d) None of the mentioned
Answer: c
Clarification: you can configure a JPA entity manage factory by providing a data source and a JPA vendor adaptor, where you can configure JPA vendor-specific information.

15. You have to register a flow execution listener in the flow executor.
a) True
b) False
Answer: a
Clarification: To have Spring Web Flow manage the persistence contexts for your web flows, you have to register a flow execution listener in the flow executor.

250+ TOP MCQs on SpringSource Tool Suite and Answers

Java Spring Multiple Choice Questions & Answers (MCQs) on “SpringSource Tool Suite”.

1. The plugin, which provides Maven support to Eclipse
a) m2eclipse
b) m2plugin
c) plugin
d) none of the mentioned
Answer: a
Clarification: The m2eclipse plugin, which provides Maven support to Eclipse (and thus to SpringSource Tool Suite), can do all the heavy lifting of importing your project since it is just a stock-standard Maven project.

2. Spring Roo provides very powerful support to bootstrap most solutions.
a) True
b) False
Answer: a
Clarification: It’s entirely possible there’s a plugin that will do the job for you.

3. A database and some sort of persistence mechanism using command:-
a) persistence setup –database HYPERSONIC_IN_MEMORY –provider HIBERNATE
b) persistence setup –database HYPERSONIC_IN_MEMORY –provider
c) persistence setup –database HYPERSONIC_IN_MEMORY
d) persistence –database HYPERSONIC_IN_MEMORY –provider HIBERNATE
Answer: a
Clarification: Enter persistence setup as it suggests. On my console, I ended up entering the following command:
roo> persistence setup –database HYPERSONIC_IN_MEMORY –provider HIBERNATE

4. persistence setup –database HYPERSONIC_IN_MEMORY –provider HIBERNATE command creates files:-
a) src/main/resources/META-INF/persistence.xml
b) src/main/resources/META-INF/spring/database.properties
c) all of the mentioned
d) none of the mentioned
Answer: c
Clarification: In my project, the command created two new files (src/main/resources/META-INF/persistence.xml and src/main/resources/META-INF/spring/database.properties), and it updated two files (src/main/resources/META-INF/spring/applicationContext.xml and pom.xml).

5. The file which contains useful configuration for Hypersonic in-memory database.
a) src/main/resources/META-INF/spring/database.properties
b) src/main/resources/META-INF/persistence.xml
c) src/main/resources/META-INF/pom.xml
d) none of the mentioned
Answer: a
Clarification: The file src/main/resources/META-INF/spring/database.properties contains useful configuration to facilitate connection to the Hypersonic in-memory database.

6. The file which is the standard JPA configuration file to enable the Hibernate-based JPA implementation.
a) src/main/resources/META-INF/spring/database.properties
b) src/main/resources/META-INF/persistence.xml
c) src/main/resources/META-INF/pom.xml
d) none of the mentioned
Answer: b
Clarification: The file src/main/resources/META-INF/persistence.xml is the standard JPA configuration file to enable the Hibernate-based JPA implementation to do its work.

7. Spring application context, src/main/resources/META-INF/spring/applicationContext.xml consists of:-
a) Data Source
b) JPA Transaction Manager
c) JPA entity manager factory
d) All of the mentioned
Answer: d
Clarification: Finally, the Spring application context, src/main/resources/META-INF/spring/applicationContext.xml, has been updated to have a data source, a JPA transaction manager, and a JPA entity manager factory.

8. Command to create a Spring MVC controller that provides a UI:-
a) controller scaff –class ~.web.CustomerController –entity ~.domain.Customer
b) controller scaff –class ~.web.CustomerController –entity
c) none of the mentioned
d) all of the mentioned
Answer: a
Clarification: Type the following command to create a Spring MVC controller that provides a UI to manipulate Customer entities (and stand back!):
controller scaff –class ~.web.CustomerController –entity ~.domain.Customer

9. To deploy the application to a web container:-
a) mvn tomcat:run
b) mvn jetty:run
c) all of the mentioned
d) none of the mentioned
Answer: c
Clarification: In the project directory, in the standard shell, run mvn tomcat:run or mvn jetty:run, and open http://localhost:8080 in your browser.

10. Spring Roo’s root folder (or any of the source packages) is:-
a) src/main/java, src/main/resources
b) src/test/java
c) src/test/resources
d) all of the mentioned
Answer: d
Clarification: The root folder (or any of the source packages, e.g., src/main/java, src/main/resources, src/test/java, or src/test/resources).

250+ TOP MCQs on JMX MBeans and Answers

Java Spring Multiple Choice Questions & Answers (MCQs) on “JMX MBeans”.

1. There are two main options for scheduling tasks on the Java platform:-
a) JDK Timer
b) Quartz Scheduler
c) All of the mentioned
d) None of the mentioned
Answer: c
Clarification: JDK Timer offers simple task scheduling features that you can use conveniently because the features are bundled with JDK. Compared with JDK Timer, Quartz offers more powerful job scheduling features.

2. Spring supports JMX by allowing you to export any beans in its IoC container as model MBeans.
a) True
b) False
Answer: a
Clarification: This can be done simply by declaring an MBeanExporter instance.

3. Connectors to expose your MBeans for remote access over a specific protocol by using a factory bean.
a) MBeanExporter
b) JSR-160
c) All of the mentioned
d) None of the mentioned
Answer: c
Clarification: In addition, Spring enables you to declare JSR-160 (Java Management Extensions Remote API) connectors to expose your MBeans for remote access over a specific protocol by using a factory bean. Spring provides factory beans for both servers and clients.

4. Spring can also detect and export your MBeans automatically from beans declared in the IoC container and annotated with JMX-specific annotations defined by Spring.
a) True
b) False
Answer: a
Clarification: The MBeanExporter class exports beans, delegating to an instance of MBeanInfoAssembler to do the heavy lifting.

5. Method, all files in the source directory will be replicated to the destination directory.
a) replicate
b) copy
c) rep
d) none of the mentioned
Answer: a
Clarification: Each time you call the replicate() method, all files in the source directory will be replicated to the destination directory. To avoid unexpected problems caused by concurrent replication, you declare this method as synchronized.

6. To register an MBean, you need an instance of the interface :-

import java.lang.management.ManagementFactory;
import javax.management.Descriptor;
import javax.management.JMException;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.modelmbean.DescriptorSupport;
import javax.management.modelmbean.InvalidTargetObjectTypeException;
import javax.management.modelmbean.ModelMBeanAttributeInfo;
import javax.management.modelmbean.ModelMBeanInfo;
import javax.management.modelmbean.ModelMBeanInfoSupport;
import javax.management.modelmbean.ModelMBeanOperationInfo;
import javax.management.modelmbean.RequiredModelMBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {<code>code>
	public static void main(String[] args) throws IOException {
		ApplicationContext context =
			new ClassPathXmlApplicationContext("beans-jmx.xml");
		FileReplicator documentReplicator =
		(FileReplicator) context.getBean("documentReplicator");
		try {
			MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
			ObjectName objectName = new ObjectName("bean:name=documentReplicator");
			RequiredModelMBean mbean = new RequiredModelMBean();
			mbean.setManagedResource(documentReplicator, "objectReference");
			Descriptor srcDirDescriptor = new DescriptorSupport(new String[] {
			"name=SrcDir", "descriptorType=attribute",
			"getMethod=getSrcDir", "setMethod=setSrcDir" });
			ModelMBeanAttributeInfo srcDirInfo = new ModelMBeanAttributeInfo(
			"SrcDir", "java.lang.String", "Source directory",
			true, true, false, srcDirDescriptor);
			Descriptor destDirDescriptor = new DescriptorSupport(new String[] {
			"name=DestDir", "descriptorType=attribute",
			"getMethod=getDestDir", "setMethod=setDestDir" });
			public static void main(String[] args) throws IOException {
			ApplicationContext context =
			new ClassPathXmlApplicationContext("beans-jmx.xml");
			FileReplicator documentReplicator =
			(FileReplicator) context.getBean("documentReplicator");
			ModelMBeanAttributeInfo destDirInfo = new ModelMBeanAttributeInfo(
			"DestDir", "java.lang.String", "Destination directory",
			true, true, false, destDirDescriptor);
			ModelMBeanOperationInfo getSrcDirInfo = new ModelMBeanOperationInfo(
			"Get source directory",
			FileReplicator.class.getMethod("getSrcDir"));
			ModelMBeanOperationInfo setSrcDirInfo = new ModelMBeanOperationInfo(
			"Set source directory",
			FileReplicator.class.getMethod("setSrcDir", String.class));
			ModelMBeanOperationInfo getDestDirInfo = new ModelMBeanOperationInfo(
			"Get destination directory",
			FileReplicator.class.getMethod("getDestDir"));
			ModelMBeanOperationInfo setDestDirInfo = new ModelMBeanOperationInfo(
			"Set destination directory",
			FileReplicator.class.getMethod("setDestDir", String.class));
			ModelMBeanOperationInfo replicateInfo = new ModelMBeanOperationInfo(
			"Replicate files",
			FileReplicator.class.getMethod("replicate"));
			ModelMBeanInfo mbeanInfo = new ModelMBeanInfoSupport(
			"FileReplicator", "File replicator",
			new ModelMBeanAttributeInfo[] { srcDirInfo, destDirInfo },
			null,
			new ModelMBeanOperationInfo[] { getSrcDirInfo, setSrcDirInfo,
			getDestDirInfo, setDestDirInfo, replicateInfo },
			null);
			mbean.setModelMBeanInfo(mbeanInfo);
			mbeanServer.registerMBean(mbean, objectName);
			} catch (JMException e) {
			...
			} catch (InvalidTargetObjectTypeException e) {
			...
			} catch (NoSuchMethodException e) {
			...
			}
			System.in.read();
	}
}

a) javax.management.MBeanServer
b) javax.management
c) javax.management.MBean
d) none of the mentioned
Answer: a
Clarification: To register an MBean, you need an instance of the interface javax.management.MBeanServer.

7.The static method to locate a platform MBean server.

import java.lang.management.ManagementFactory;
import javax.management.Descriptor;
import javax.management.JMException;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.modelmbean.DescriptorSupport;
import javax.management.modelmbean.InvalidTargetObjectTypeException;
import javax.management.modelmbean.ModelMBeanAttributeInfo;
import javax.management.modelmbean.ModelMBeanInfo;
import javax.management.modelmbean.ModelMBeanInfoSupport;
import javax.management.modelmbean.ModelMBeanOperationInfo;
import javax.management.modelmbean.RequiredModelMBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
	public static void main(String[] args) throws IOException {
		ApplicationContext context =
			new ClassPathXmlApplicationContext("beans-jmx.xml");
		FileReplicator documentReplicator =
		(FileReplicator) context.getBean("documentReplicator");
		try {
			MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
			ObjectName objectName = new ObjectName("bean:name=documentReplicator");
			RequiredModelMBean mbean = new RequiredModelMBean();
			mbean.setManagedResource(documentReplicator, "objectReference");
			Descriptor srcDirDescriptor = new DescriptorSupport(new String[] {
			"name=SrcDir", "descriptorType=attribute",
			"getMethod=getSrcDir", "setMethod=setSrcDir" });
			ModelMBeanAttributeInfo srcDirInfo = new ModelMBeanAttributeInfo(
			"SrcDir", "java.lang.String", "Source directory",
			true, true, false, srcDirDescriptor);
			Descriptor destDirDescriptor = new DescriptorSupport(new String[] {
			"name=DestDir", "descriptorType=attribute",
			"getMethod=getDestDir", "setMethod=setDestDir" });
			public static void main(String[] args) throws IOException {
			ApplicationContext context =
			new ClassPathXmlApplicationContext("beans-jmx.xml");
			FileReplicator documentReplicator =
			(FileReplicator) context.getBean("documentReplicator");
			ModelMBeanAttributeInfo destDirInfo = new ModelMBeanAttributeInfo(
			"DestDir", "java.lang.String", "Destination directory",
			true, true, false, destDirDescriptor);
			ModelMBeanOperationInfo getSrcDirInfo = new ModelMBeanOperationInfo(
			"Get source directory",
			FileReplicator.class.getMethod("getSrcDir"));
			ModelMBeanOperationInfo setSrcDirInfo = new ModelMBeanOperationInfo(
			"Set source directory",
			FileReplicator.class.getMethod("setSrcDir", String.class));
			ModelMBeanOperationInfo getDestDirInfo = new ModelMBeanOperationInfo(
			"Get destination directory",
			FileReplicator.class.getMethod("getDestDir"));
			ModelMBeanOperationInfo setDestDirInfo = new ModelMBeanOperationInfo(
			"Set destination directory",
			FileReplicator.class.getMethod("setDestDir", String.class));
			ModelMBeanOperationInfo replicateInfo = new ModelMBeanOperationInfo(
			"Replicate files",
			FileReplicator.class.getMethod("replicate"));
			ModelMBeanInfo mbeanInfo = new ModelMBeanInfoSupport(
			"FileReplicator", "File replicator",
			new ModelMBeanAttributeInfo[] { srcDirInfo, destDirInfo },
			null,
			new ModelMBeanOperationInfo[] { getSrcDirInfo, setSrcDirInfo,
			getDestDirInfo, setDestDirInfo, replicateInfo },
			null);
			mbean.setModelMBeanInfo(mbeanInfo);
			mbeanServer.registerMBean(mbean, objectName);
			} catch (JMException e) {
			...
			} catch (InvalidTargetObjectTypeException e) {
			...
			} catch (NoSuchMethodException e) {
			...
			}
			System.in.read();
	}
}

a) ManagementFactory.getPlatform()
b) ManagementFactory.getPlatformMBeanServer()
c) ManagementFactory.getPlatformMBean()
d) All of the mentioned
Answer: b
Clarification: It will create an MBean server if none exists and then register this server instance for future use.

8.From the preceding code, you can see that for each MBean attribute and MBean operation, you need to create a:-

import java.lang.management.ManagementFactory;
import javax.management.Descriptor;
import javax.management.JMException;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.modelmbean.DescriptorSupport;
import javax.management.modelmbean.InvalidTargetObjectTypeException;
import javax.management.modelmbean.ModelMBeanAttributeInfo;
import javax.management.modelmbean.ModelMBeanInfo;
import javax.management.modelmbean.ModelMBeanInfoSupport;
import javax.management.modelmbean.ModelMBeanOperationInfo;
import javax.management.modelmbean.RequiredModelMBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
	public static void main(String[] args) throws IOException {
		ApplicationContext context =
			new ClassPathXmlApplicationContext("beans-jmx.xml");
		FileReplicator documentReplicator =
		(FileReplicator) context.getBean("documentReplicator");
		try {
			MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
			ObjectName objectName = new ObjectName("bean:name=documentReplicator");
			RequiredModelMBean mbean = new RequiredModelMBean();
			mbean.setManagedResource(documentReplicator, "objectReference");
			Descriptor srcDirDescriptor = new DescriptorSupport(new String[] {
			"name=SrcDir", "descriptorType=attribute",
			"getMethod=getSrcDir", "setMethod=setSrcDir" });
			ModelMBeanAttributeInfo srcDirInfo = new ModelMBeanAttributeInfo(
			"SrcDir", "java.lang.String", "Source directory",
			true, true, false, srcDirDescriptor);
			Descriptor destDirDescriptor = new DescriptorSupport(new String[] {
			"name=DestDir", "descriptorType=attribute",
			"getMethod=getDestDir", "setMethod=setDestDir" });
			public static void main(String[] args) throws IOException {
			ApplicationContext context =
			new ClassPathXmlApplicationContext("beans-jmx.xml");
			FileReplicator documentReplicator =
			(FileReplicator) context.getBean("documentReplicator");
			ModelMBeanAttributeInfo destDirInfo = new ModelMBeanAttributeInfo(
			"DestDir", "java.lang.String", "Destination directory",
			true, true, false, destDirDescriptor);
			ModelMBeanOperationInfo getSrcDirInfo = new ModelMBeanOperationInfo(
			"Get source directory",
			FileReplicator.class.getMethod("getSrcDir"));
			ModelMBeanOperationInfo setSrcDirInfo = new ModelMBeanOperationInfo(
			"Set source directory",
			FileReplicator.class.getMethod("setSrcDir", String.class));
			ModelMBeanOperationInfo getDestDirInfo = new ModelMBeanOperationInfo(
			"Get destination directory",
			FileReplicator.class.getMethod("getDestDir"));
			ModelMBeanOperationInfo setDestDirInfo = new ModelMBeanOperationInfo(
			"Set destination directory",
			FileReplicator.class.getMethod("setDestDir", String.class));
			ModelMBeanOperationInfo replicateInfo = new ModelMBeanOperationInfo(
			"Replicate files",
			FileReplicator.class.getMethod("replicate"));
			ModelMBeanInfo mbeanInfo = new ModelMBeanInfoSupport(
			"FileReplicator", "File replicator",
			new ModelMBeanAttributeInfo[] { srcDirInfo, destDirInfo },
			null,
			new ModelMBeanOperationInfo[] { getSrcDirInfo, setSrcDirInfo,
			getDestDirInfo, setDestDirInfo, replicateInfo },
			null);
			mbean.setModelMBeanInfo(mbeanInfo);
			mbeanServer.registerMBean(mbean, objectName);
			} catch (JMException e) {
			...
			} catch (InvalidTargetObjectTypeException e) {
			...
			} catch (NoSuchMethodException e) {
			...
			}
			System.in.read();
	}
}

a) ModelMBeanAttributeInfo
b) ModelMBeanOperationInfo
c) None of the mentioned
d) All of the mentioned
Answer: d
Clarification: From the preceding code, you can see that for each MBean attribute and MBean operation, you need to create a ModelMBeanAttributeInfo object and a ModelMBeanOperationInfo object for describing it.

9. VM argument to enable local monitoring of this application.
a) -Dcom.sun.management.jmxremote
b) -Dcom.sun.management
c) -Dcom.sun.management.jmx
d) None of the mentioned
Answer: a
Clarification: You have to add the VM argument -Dcom.sun.management.jmxremote to enable local monitoring of this application. You should also include all other options for your command, such as the classpath, as necessary.
Java –classpath … -Dcom.sun.management.jmxremote com.apress.springrecipes.replicator.Main

10. However, in an environment with no MBean server available, you have to create one explicitly using:-
a) MBeanServerFactoryBean
b) MBeanServerFactory
c) All of the mentioned
d) None of the mentioned
Answer: a
Clarification: To make your application portable to different runtime environments, you should enable the locateExistingServerIfPossible property so that this factory bean will create an MBean server only if none is available.

11. Spring allows you to create a JMX connector server through:-
a) ConnectorServerFactoryBean
b) ConnectorServer
c) ConnectorServerFactory
d) All of the mentioned
Answer: a
Clarification: By default, ConnectorServerFactoryBean creates and starts a JMX connector server bound to the service URL service:jmx:jmxmp://localhost:9875, which exposes the JMX connector through the JMX Messaging Protocol (JMXMP).

12. ? should be replaced by:-

<beans ...>
	...
	<bean id="rmiRegistry"
	class="org.springframework.remoting.rmi.RmiRegistryFactoryBean" />
	<bean id="connectorServer"
	class="org.springframework.jmx.support.ConnectorServerFactoryBean"
	depends-on="rmiRegistry">
	<property name="serviceUrl" value=? />
	bean>
beans>

a) service:jmx:rmi://localhost/jndi/rmi://localhost:1099/replicator
b) service:jmx:rmi://localhost/jndi/rmi://localhost:1099/
c) service:jmx:rmi://localhost/jndi//localhost:1099/replicator
d) none of the mentioned
Answer: a
Clarification: To expose your JMX connector through a specific protocol, you just provide the service URL for it.

13. If no RMI registry has been created externally, you should create one by using:-
a) RmiRegistryFactory
b) RmiRegistryFactoryBean
c) RmiRegistry
d) RmiRegister
Answer: b
Clarification: If no RMI registry has been created externally, you should create one by using RmiRegistryFactoryBean. The default port for this registry is 1099, but you can specify another one in its port property.

14. The simplest MBean assembler in Spring is, which allows you to specify the names of the methods to export.
a) MethodNameBasedMBeanInfoAssembler
b) MethodNameBasedMBeanInfo
c) MethodNameBasedMBean
d) MethodNameBasedInfoAssembler
Answer: a
Clarification: The simplest MBean assembler in Spring is MethodNameBasedMBeanInfoAssembler, which allows you to specify the names of the methods to export.

15. Spring allows your beans to publish JMX notifications through:-
a) NotificationPublisher
b) Notification
c) Notify
d) All of the mentioned
Answer: a
Clarification: Spring allows your beans to publish JMX notifications through the NotificationPublisher interface. You can also register standard JMX notification listeners in the IoC container to listen to JMX notifications.

250+ TOP MCQs on Getting Started with OSGi and Answers

Advanced Java Spring Questions & Answers on “Getting Started with OSGi”.

1. OSGi—which was formerly known as the:-
a) Open Services Gateway initiative
b) Open Source Gateway initiative
c) Open Services Gateway initialisation
d) None of the mentioned
Answer: a
Clarification: OSGi—which was formerly known as the Open Services Gateway initiative, though the name’s obsolete now—has its roots in the embedded space, where dynamic service provisioning is far more important than it is in the gridiron world of enterprise applications.

2. OSGi provides a layer on top of the JVM’s default class loader.
a) True
b) False
Answer: a
Clarification: The deployment unit for OSGi is a bundle, which is essentially a JAR with an augmented MANIFEST.MF.

3. On top of Spring Dynamic Modules, SpringSource built SpringSource dm Server, which is a server wired from top to bottom with OSGi and Spring.
a) True
b) False
Answer: a
Clarification: SpringSource dm Server supports dynamic deployment, enhanced tooling, HTTP, and native .war deployment.

4. OSGi is a framework.
a) True
b) False
Answer: b
Clarification: OSGi is a specification, not a framework. There are many implementations of the specification, just as there are many implementations of the Java EE specification.

5. User component models are:-
a) OSGi
b) Spring
c) All of the mentioned
d) None of the mentioned
Answer: b
Clarification: OSGi is not a user component model, like Spring or EJB 3. Instead, it sits below your components, providing life-cycle management for Java classes.

6. In OSGi, anything used by something else is a state.
a) True
b) False
Answer: b
Clarification: In OSGi, anything used by something else is a service. “Service” doesn’t imply any concrete inheritance.

7. “Service” doesn’t imply any:-
a) RPC
b) inheritance
c) transactional qualities
d) all of the mentioned
Answer: d
Clarification: “Service” doesn’t imply any concrete inheritance; it doesn’t imply transactional qualities, and it doesn’t imply RPC. It’s merely a class on whose concrete, black-box functionality and interface your class relies.

8. OSGi bundles are simply standard .jar files with customized MANIFESTs that OSGi consumes at runtime.
a) True
b) False
Answer: a
Clarification: The plug-in wraps the bnd command line tool.

9. Tool which dynamically interrogates classes for their imports and generates OSGi–compliant entries.
a) pnd
b) jndi
c) bnd
d) none of the mentioned
Answer: c
Clarification: We repeat it here mainly for illustrative purposes.

10. The plug-in produces OSGi–compliant bundles that work in any container.
a) True
b) False
Answer: c
Clarification: To read more on the plug-in itself, see http://felix.apache.org/site/apache-felix-maven-bundle-plugin-bnd.html.

11. The Bundle-Activator directive describes to the OSGi environment, which class implements :-
a) BundleActivator
b) BundleActivate
c) All of the mentioned
d) None of the mentioned
Answer: a
Clarification: The Bundle-Activator directive describes to the OSGi environment, which class implements BundleActivator, and should be consulted when life cycle events occur.

12. When the bundle begins to load and start, it calls the start method of the:-
a) BundleActivator
b) Activator
c) All of the mentioned
d) None of the mentioned
Answer: b
Clarification: When the bundle begins to load and start, it calls the start method of the Activator.

13. To start using Spring to smooth over some of the minutiae of resource acquisition and to help build more reliable systems in an OSGi environment.
a) Spring DM server
b) Spring Dynamic Modules
c) All of the mentioned
d) None of the mentioned
Answer: b
Clarification: Use Spring Dynamic Modules to provide the integration. Spring Dynamic Modules is a framework on top of OSGi that works with any OSGi environment.

14. Spring Dynamic Modules scans our deployed bundles and loads an ApplicationContext (actually, the specific type of the ApplicationContext is OsgiBundleXmlApplicationContext) into memory based on an event, or a trigger.
a) True
b) False
Answer: a
Clarification: There are two ways to trigger this behavior. The first is to explicitly specify in the META-INF/MANIFEST.MF file the attribute Spring-Context, which allows you to override the default location it consults. Otherwise, by default, Spring Dynamic Modules will look for the XML file in the META-INF/spring directory of a bundle.

15. You’ll split your OSGi–specific Spring configuration and your plain-vanilla Spring configuration into:-
a) modulename-context.xml
b) modulename-osgi-context.xml
c) all of the mentioned
d) none of the mentioned
Answer: a
Clarification: Typically, you’ll split your OSGi–specific Spring configuration and your plain-vanilla Spring configuration into two different files, of the form: modulename-context.xml and modulename-osgi-context.xml.


To practice advanced questions on all areas of Java Spring,

250+ TOP MCQs on Declaring Beans and Answers

Java Spring Multiple Choice Questions & Answers (MCQs) on “Declaring Beans”.

1. Declaring Beans using:-
a) Static field
b) Object Properties
c) All of the mentioned
d) None of the mentioned
Answer: c
Clarification: Beans can be declared from static fields as well as Object properties.

2. Ways to declare bean from a static field?
a) FieldRetrievingFactoryBean
b) util:contant
c) All of the mentioned
d) None of the mentioned
Answer: c
Clarification: To declare a bean from a static field, you can make use of either the built-in factory bean FieldRetrievingFactoryBean, or the util:constant tag in Spring 2.x.

3. Declaring a bean from a static field requires a built-in factory bean FieldRetrievingFactoryBean and fully qualified field name or instance field is specified in the list property.
a) True
b) False
Answer: b
Clarification: StaticField property is used to specify instance field name.

4. A)

      public abstract class Product {
	public static final Product AAA = new Battery("AAA", 2.5);
	public static final Product CDRW = new Disc("CD-RW", 1.5);
	...
      }
      <beans ...>
	<bean id="aaa" class="org.springframework.beans.factory.config.
	FieldRetrievingFactoryBean">
	<property name="staticField">
	<value>com.shop.Product.AAAvalue>
	property>
	bean>
	<bean id="cdrw" class="org.springframework.beans.factory.config.
	FieldRetrievingFactoryBean">
	<property> name="staticField"
	valuecom.shop.Product.CDRW/value
	property>
	bean>
     beans>
 
   B) Product aaa = com.shop.Product.AAA;
      Product cdrw = com.shop.Product.CDRW;

a) A and B are equivalent
b) A and B provides different functionality
c) Runtime Error in A
d) Exception in B
Answer: a
Clarification: StaticField method fills up the static fields with the provided property values.

5. As an alternative to specifying the field name in the staticField property explicitly, you can set it as the bean name of FieldRetrievingFactoryBean.
a) True
b) False
Answer: a
Clarification: Bean name may get rather long and verbose.

6. Is this bean configuration metadata correct?

   <beans ...>
	bean id="com.shop.Product.AAA"
	class="org.springframework.beans.factory.config.
	FieldRetrievingFactoryBean" /
	bean id="com.shop.Product.CDRW"
	class="org.springframework.beans.factory.config.
	FieldRetrievingFactoryBean" /
   beans>

a) Yes
b) No
Answer: a
Clarification: This is an alternate method of using staticField in property attributes.

7. Which tag is also allowed by static field?
a) util:constant
b) list
c) set
d) constructor-args
Answer: a
Clarification: Spring 2 and later allow you to declare a bean from a static field by using the util:constant tag.

8. Is this bean configuration correct?

    <beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
	http://www.springframework.org/schema/util/spring-util-3.0.xsd"
	util:constant id="aaa"
	static-field="com.shop.Product.AAA" />
	util:constant id="cdrw"
	static-field="com.shop.Product.CDRW" />
  beans>

a) Yes
b) No
Answer: b
Clarification: Schema for util:constant needs to be included using this link: http://www.springframework.org/schema/util.

9. Declaring bean form object properties can be done using:-
a) PropertyPathFactoryBean
b) util:constant
c) None of the mentioned
d) All of the mentioned
Answer: a
Clarification: To declare a bean from an object property or a property path, you can make use of either the built-in factory bean PropertyPathFactoryBean or the util:property-path tag in Spring 2.x.

10. Inner Bean can be retrieved by it’s name.
a) True
b) False
Answer: b
Clarification: Since inner beans are local to another bean, so can’t be accessed globally.

11. PropertyPathFactoryBean declares a bean from an:-
a) Object Property
b) Property Path
c) All of the mentioned
d) None of the mentioned
Answer: c
Clarification: The factory bean PropertyPathFactoryBean can be used to declare a bean from an object property or a property path.

12. The propertyPath property of PropertyPathFactoryBean can accept only a single property name.
a) True
b) False
Answer: b
Clarification: The propertyPath property of PropertyPathFactoryBean can accept not only a single property name but also a property path with dots as the separators.

13. Alternate way of PropertyPathFactoryBean to declare a bean.
a) util:property-path tag
b) util:constant tag
c) None of the mentioned
d) All of the mentioned
Answer: a
Clarification: Compared to using PropertyPathFactoryBean, it is a simpler way of declaring beans from properties.

14. We can combine target Object and propertyPath properties as bean name/id of PropertyPathFactoryBean.
a) True
b) False
Answer: a
Clarification: In addition to specifying the targetObject and propertyPath properties explicitly, you can combine them as the bean name of PropertyPathFactoryBean. The downside is that your bean name may get rather long and verbose.

15. The Spring Expression Language can be accessed by:-
a) XML configuration
b) Annotations
c) None of the mentioned
d) All of the mentioned
Answer: d
Clarification: The expression language is available via XML or annotations.