Spring 注解式依赖注入

创建一个Spring项目

Spring项目快速创建查看此链接:https://blog.csdn.net/Kedongyu_/article/details/81392992

查看context.xml是否开启扫描

在context.xml文件添加下列代码,启用注解式依赖注入。

<context:component-scan base-package="com.diko.first"/>                

其中base-package的值改为所要扫描的包路径。这里设置为 com.diko.first包下的所有类。

注解的类别:

@Component 任何一个交给Spring管理的类都可以使用@Component注解来注释。@Component注解基本可以放在任何可受Spring管理的类的头上,但是@Component不推荐使用,尽量使用下面三个代替。

@Repository 主要用于注释Dao层的Bean,效果等效于@Component,但是使用范围仅限于Dao层

@Service 主要用于注释业务层的Bean,效果等效与@Component,但是使用范围仅限于业务层。

@Controller 主要用于注释控制层的Bean,效果等效与@Component,但是使用范围仅限于控制层,也就是Strut框架中的Action,或者Spring MVC中的Controller。

@Autowired 注释可以在 setter 方法中被用于自动连接 bean,当 Spring遇到一个在 setter 方法中使用的 @Autowired 注释,它会在方法中视图执行 byType 进行自动连接。

@Required 注释应用于 bean 属性的 setter 方法,它表明受影响的 bean 属性在配置时必须放在 XML 配置文件中,否则容器就会抛出一个 BeanInitializationException 异常。

@Qualifier 可以使用 @Qualifier 注释和 @Autowired 注释通过指定哪一个真正的 bean 将会被装配来消除混乱。

@Resource 与@Autowired注解大致一致,但是@Resource默认按照名称(byName)方式进行bean匹配,而@Autowired默认按照类型(byType)方式进行bean匹配。

 

各个注解的使用实例

@Component 未指定Bean id,将类交给Spring 管理:

@Component
@Aspect
public class AllServicePointCut {
	@Pointcut("execution(* com.diko.first.service.impl.*.*(..))")
	public void allServicePoint() {
	}
}

@Component 指定Bean id,将类交给Spring 管理:

@Component("allServicePointCut")
@Aspect
public class AllServicePointCut {
	@Pointcut("execution(* com.neusoft.first.service.impl.*.*(..))")
	public void allServicePoint() {
	}

}

@Repository 注解,这个给出指定id的写法,未指定id写法同上

@Repository("exceptionLogDao")
public class ExceptionLogDaoImpl implements IExceptionLogDao {

	private DataSource dataSource=null;
	
	@Autowired
	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}
	
	@Override
	public void add(ExceptionLogModel exceptionLog) throws Exception {
		Connection conn=dataSource.getConnection();
		String sql = "insert into OA_EXceptionLog values(EXCEPTIONLOG_PK_SQ.nextval,?,?,?,?)";
		PreparedStatement ps=conn.prepareStatement(sql);
		ps.setString(1, exceptionLog.getExMessage());
		ps.setDate(2, new Date(exceptionLog.getExTime().getTime()));
		ps.setString(3, exceptionLog.getExClassName());
		ps.setString(4, exceptionLog.getExMethod());
		ps.executeUpdate();
		ps.close();
		conn.close();
	}
}

@Service 的使用,类似@Repository

@Service
public class MailServiceImpl implements IMailService {
	@Override
	public void sendMail(String title, String content) throws Exception {
			// 使用java mail API
			Properties prop=new Properties();
			prop.setProperty("main.host","10.1.53.30");
			prop.setProperty("main.transport.protocol","smpt");
			prop.setProperty("main.smtp.auth","false");
			//连接到邮局服务器
			Session session= Session.getInstance(prop);
			//创建邮件
			Message message=new MimeMessage(session);
			//创建发件邮箱
			Address sender=new InternetAddress("[email protected]");
			message.setFrom(sender);
			//创建接受邮箱
			Address to=new InternetAddress("[email protected]");
			message.setRecipient(RecipientType.TO, to);
			message.setSubject(title);
			message.setText(content);
			Transport.send(message);
	}

}

@Controller 类似于@Service@Repository用法,这里不给出Demo。

@Autowired 的使用,通过ByType进行依赖注入

@Aspect
public class ServiceMethodAdvice {
	
	private IMailService mailservice=null;
	
	@Autowired
	public void setMailservice(IMailService mailservice) {
		this.mailservice = mailservice;
	}

	@AfterThrowing(value="AllServicePointCut.allServicePoint()",throwing="exception")
	public void serviceExceptionHandler(JoinPoint jp,Exception exception) throws Exception {
		mailservice.sendMail("异常",exception+"");
	}
	
}

@Required 表明受影响的 bean 属性在配置时必须放在 XML 配置文件中,否则抛出异常,这里不给出Demo。

@Qualifier 通过指定id(ByName)进行依赖注入

@Aspect
@Component
public class ServiceMethodAdvice {
	
	private IExceptionLogDao exceptionLogDao=null;
	
	@Autowired
	@Qualifier("exceptionLogDao")
	public void setExceptionLogDao(IExceptionLogDao exceptionLogDao) {
		this.exceptionLogDao = exceptionLogDao;
	}
	
	@Around(value="AllServicePointCut.allServicePoint()")
	public Object runAroundMethod(ProceedingJoinPoint pjp) throws Throwable{
		ServiceRunTimeModel srtm=new ServiceRunTimeModel();
		srtm.setRunDate(new Date());
		srtm.setClassName(pjp.getTarget().getClass().getName());
		srtm.setMethodName(pjp.getSignature().getName());
		long pre=new Date().getTime();	
		Object obj=pjp.proceed();	
		long now=new Date().getTime();
		srtm.setRunTime((int)(now-pre));
		serviceRunTimeDao.add(srtm);
		return obj;
	}
}

@Resource 的使用

@Aspect
@Component
public class ServiceMethodAdvice {
	
	private IExceptionLogDao exceptionLogDao=null;
	
	@Resource
	public void setExceptionLogDao(IExceptionLogDao exceptionLogDao) {
		this.exceptionLogDao = exceptionLogDao;
	}
	
	@Around(value="AllServicePointCut.allServicePoint()")
	public Object runAroundMethod(ProceedingJoinPoint pjp) throws Throwable{
		ServiceRunTimeModel srtm=new ServiceRunTimeModel();
		srtm.setRunDate(new Date());
		srtm.setClassName(pjp.getTarget().getClass().getName());
		srtm.setMethodName(pjp.getSignature().getName());
		long pre=new Date().getTime();	
		Object obj=pjp.proceed();	
		long now=new Date().getTime();
		srtm.setRunTime((int)(now-pre));
		serviceRunTimeDao.add(srtm);
		return obj;
	}
}

猜你喜欢

转载自blog.csdn.net/Kedongyu_/article/details/81393198