Spring学习之用注解配置依赖注入

1.加入aop相关的jar包

Spring学习之用注解配置依赖注入_第1张图片

2.配置applicationContext.xml(切记,放在src目录下)




	

 3.在类上增加注解 @Component

UserService

package com.user.service;

import javax.annotation.Resource;

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

import com.user.dao.BookDao;
import com.user.dao.UserDao;

@Service(value="us")
public class UserService {
	
	//@Autowired
	private UserDao userDao;
	
	//@Autowired
	private BookDao bookDao;
	
	
	public UserDao getUserDao() {
		return userDao;
	}
	
	@Resource(name="userDao")
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public BookDao getBookDao() {
		return bookDao;
	}
	
	@Resource(name="bookDaoImpl2")
	public void setBookDao(BookDao bookDao) {
		this.bookDao = bookDao;
	}

}

UserDao:

package com.user.dao;

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

import com.user.aop.User;

@Component
public class UserDao {

	@Autowired
	private User user;

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
}

User:

package com.user.aop;

import org.springframework.stereotype.Component;

@Component
public class User implements UserI {
	public void say() {
		System.out.println("Hello Spring");
	}
}

User的接口:

package com.user.aop;

public interface UserI {
	public void say();
}

BookDAO:

package com.user.dao;

public interface BookDao {

}

BookDaoImpl

package com.user.dao;

import org.springframework.stereotype.Repository;

@Repository
public class BookDaoImpl implements BookDao{

}

BookDaoImpl2

package com.user.dao;

import org.springframework.stereotype.Repository;

@Repository
public class BookDaoImpl2 implements BookDao{

}

测试类:

package com.user.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.user.aop.User;
import com.user.service.UserService;

public class UserServiceTest {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		UserService service = (UserService)context.getBean("us");
		System.out.println(service);
	}
}

 

你可能感兴趣的:(Spring,Spring,注解配置)