spring注解开发

spring的bean管理(注解)

注解介绍:

  1.  代码里面特殊标记,使用注解可以完成功能
  2.  注解写法@注解名称(属性名=属性名)
  3.  注解使用类上面,方法上面和属性下面

spring注解开发准备:

1、导入jar包(4个核心包,与两个日志包),导入aop的jar包

2、创建类,创建方法

3、创建spring配置文件,引入约束

(1)做ioc的基本功能,引入约束beans

打开G:\spring-framework-4.3.7.RELEASE\docs\spring-framework-reference\html,里面的最后一个文件,找到该部分,粘贴:

spring注解开发_第1张图片

(2)做spring的ioc注解开发,引入新的约束

bean.xml


 
        


User.java

@Component(value = "user")
// 相当于
public class User {
	public void add() {
		System.out.println("add()");
	}
}

测试:

public class TestAnno {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				"bean2.xml");
		User user = (User) context.getBean("user");
		user.add();
		System.err.println(user);

	}
}

创建对象有四个注解:

spring中提供@Component的三个衍生注解(功能来讲一样):

  1. @controller     web层
  2. @service         业务层
  3. @Repository   持久层
这三个注解是为了让标注类本身的用途清晰,spring在后续版本对其增强:

注解注入属性:

1、创建service类,创建dao类,在service得到dao对象
进入属性第一个注解@Autowored
UserDao.java
@Component(value = "userdao")
public class UserDao {

	public void add() {
		System.out.println("userdao.add()");
	}
}
UserService.java
@Service(value="userservice")
public class UserService {
	@Autowired
	private UserDao userDao;
	public void add()
	{
		System.out.println("service");
		userDao.add();
	}

}
测试:
public class TestAnno2 {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				"bean2.xml");
		UserService userService = (UserService) context.getBean("userservice");
		userService.add();
	}

}
2、注入属性第二个注解,@Resource
UserDao.java
@Component(value = "userdao")
public class UserDao {

	public void add() {
		System.out.println("userdao.add()");
	}
}
UserService.java
@Service(value="userservice")
public class UserService {
	@Resource(name="userdao")
	private UserDao userDao;
	public void add()
	{
		System.out.println("service");
		userDao.add();
	}
}
测试:
public class TestAnno2 {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				"bean2.xml");
		UserService userService = (UserService) context.getBean("userservice");
		userService.add();
	}

}

配置文件和注解混合使用:

1、创建对象操作使用配置文件方式实现
2、注入属性操作使用注解方式实现

BookSerivce.java
public class BookService {
	@Resource(name="bookDao")
	private BookDao bookDao;
	@Resource(name="orderDao")
	private OrderDao orderDao;
	public void add()
	{
		System.out.println("bookservice");
		bookDao.book();
		orderDao.buy();
	}

}
BookDao.java
public class BookDao {
	public void book()
	{
		System.out.println("book dao");
	}

}
OrderDao.java
public class OrderDao {
	public void buy()
	{
		System.out.println("orderdao.buy()");
	}

}
bean2.xml

 
        






测试:
public class TestAnno3 {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				"bean2.xml");
		BookService bookService  = (BookService) context.getBean("bookService");
		bookService.add();
	}

}


你可能感兴趣的:(Spring)