首先先了解其中的注解都是做什么的,用在什么地方:
@Autowired 自动按照类型依赖注入,可以对成员变量,方法及构造函数进行标注
@Resource 自动按照名称依赖注入,可以对成员变量,方法及构造函数进行标注
@Controller 通常标注控制层
@Service 通常标注业务层
@Repository 通常标注数据访问层(DAO)
@Component 泛指组件,用于不好分类是的标注
@Scope bean的作用域(property)
下面是基于Set方法的例子:
D层的实现类:
package com.spring.dao;
import org.springframework.stereotype.Repository;
@Repository("userDao")
public class UserDaoImpl implements UserDao {
@Override
public void addUser() {
System.out.println("addUser");
}
}
Service的实现类:
package com.spring.service;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.spring.dao.UserDao;
@Service("userService")
public class UserServiceImpl implements UserService {
private UserDao userDao;
@Autowired
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
public void addUser() {
userDao.addUser();
}
}
Client类:
package com.spring.client;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.spring.config.ApplicationConfig;
import com.spring.service.UserService;
import com.spring.service.UserServiceImpl;
public class Client {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicatioinContext=
new AnnotationConfigApplicationContext(ApplicationConfig.class);
UserService userService=
applicatioinContext.getBean("userService",UserService.class);
userService.addUser();
}
}
配置类:
package com.spring.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages={"com.spring"})
public class ApplicationConfig {
}