package com.wyj.annotation;
import java.lang.annotation.Target;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)// 注解会在class字节码文件中存在,在运行时可以通过反射获取到
@Documented
@Inherited
public @interface AutoWire
{
public String name();
}
注解的工厂类
package com.wyj.annotation.factory;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import com.wyj.annotation.AutoWire;
/**
* 注解的工厂类
*
* @author 王宜君
*/
public class AnnotationFactory
{
public static Object getBean( Class<?> t )
throws InstantiationException, IllegalAccessException, SecurityException,
NoSuchMethodException, IllegalArgumentException,
InvocationTargetException, ClassNotFoundException
{
Object obj = t.newInstance();
Field[] fields = t.getDeclaredFields();
for ( Field f : fields )
{
// 首先判断改域有没有AutoWire的注解:
if ( f.isAnnotationPresent( AutoWire.class ) )
{
// 有的话便得到它的注解类:
AutoWire wire = f.getAnnotation( AutoWire.class );
// 得它的注解类name的属性值,我们要利用他反射成一个对象赋予传进来的Class类型的对象:
String clazzName = wire.name();
// 下面便是反射的一些基本用法:
Object inject = Class.forName( clazzName ).newInstance();
String fieldName = f.getName();
String mName = fieldName.substring( 0, 1 ).toUpperCase()
+ fieldName.substring( 1 );
Method method = t.getMethod( "set" + mName, f.getType() );
method.invoke( obj, inject );
return obj;
}
}
return null;
}
}
注解的dao类
package com.wyj.dao;
import com.wyj.annotation.entity.Employee;
public class EmployeeDao
{
public void save( Employee emp )
{
System.out.println( emp );
System.out.println( emp.getId() + "," + emp.getName() + ","
+ emp.getSalary() );
System.out.println( "emp have saved." );
}
}
注解的业务类
package com.wyj.service;
import com.wyj.annotation.AutoWire;
import com.wyj.annotation.entity.Employee;
import com.wyj.dao.EmployeeDao;
public class EmployeeService
{
@AutoWire( name = "com.wyj.dao.EmployeeDao" )
private EmployeeDao dao;
public EmployeeDao getDao()
{
return dao;
}
public void setDao( EmployeeDao dao )
{
this.dao = dao;
}
public void save()
{
Employee emp = new Employee();
emp.setId( 246 );
emp.setName( "brzone@126.com" );
emp.setSalary( 8888 );
dao.save( emp );
}
}
注解的测试类
package com.wyj.annotation.test;
import com.wyj.annotation.factory.AnnotationFactory;
import com.wyj.service.EmployeeService;
public class AnnotationClientTest
{
public static void main( String[] args ) throws Exception
{
EmployeeService service = (EmployeeService)
AnnotationFactory.getBean( EmployeeService.class );
service.save();
}
}