天天看点

Spring 框架总结(四) :基于注解的依赖注入

基于xml配置文件的依赖注入

首先更改xml文件:

<context:component-scan base-package="sdibt.fly"></context:component-scan>

定义包的扫描范围,sdibt.fly包下的类如果打了@Controller、@Service、@Repository、@Component注解,这个类就好比在xml配置文件下配置了bean标签

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="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/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

<context:component-scan base-package="sdibt.fly"></context:component-scan>

</beans>
           

四种注解方式的却别:

1.@Controller作用在Controller层

2.@Service作用在Service层

3.@Repository作用在Dao层

4.@Component作用在普通的pojo对象

Action:action类上需要的注解是@Controller,@Autowired打在属性或者set方法上,默认是是根据类型自动组装

package sdibt.fly.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import sdibt.fly.service.UserService;
@Controller
public class UserAction {
	//默认按照类型自动装配
	@Autowired
	private UserService userService;	
	
	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public void addUser(){
		userService.addUser();
	}
}
           

Service:@Autowired

package sdibt.fly.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import sdibt.fly.dao.UserDao;
@Service
public class UserService {
	@Autowired
	private UserDao userDao;

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}


	public void addUser(){
		userDao.addUser();
	}
}
           

dao:@Repository

package sdibt.fly.dao;

import org.springframework.stereotype.Repository;

@Repository
public class UserDao {
	public void addUser(){
		System.out.println("addUser");
	}
}
           

除了使用@Autowired,还可以使用@Resource,默认是先按照名字自动装配,如果找不到对应的名字,就会按照类型自动装配

--定义Bean的作用域和生命过程

@Scope("prototype")

值有:singleton,prototype,session,request,session,globalSession

@PostConstruct 

相当于init-method,使用在方法上,当Bean初始化时执行。

@PreDestroy 

相当于destory-method,使用在方法上,当Bean销毁时执行。

继续阅读