In Spring automatically detecting classes are @Repository, @Service, and @Controller. In this example using @Repository annotations in side bean and adding component scane in spring configuration xml file. In Persistence layer ,@Repository supports as a marker for automatic exception translation.
Create a Bean with @Repository
package com.pretech;import org.springframework.stereotype.Repository;@Repository("repo")public class Employee {public String getName() {return"Vinod";}public String getAddress() {return"bangalore";}}
Update component scan details in spring configuration file (SpringContext.xml)
<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsd"><context:component-scanbase-package="com.pretech"/></beans>
Create a Main class to test @Repository
package com.pretech;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class RepositoryTest {public static void main(String[] args) {ApplicationContext context = new ClassPathXmlApplicationContext("SpringContext.xml");Employee emp =(Employee) context.getBean("repo");System.out.println(emp.getName());System.out.println(emp.getAddress());}}
Ouput
Vinod
bangalore
No comments:
Post a Comment