1.Spring针对Bean管理中的创建对象提供注解
1.@Component
2.@Service (一般用于service层)
3.@Controller(一般用于web层)
4.@Repository(一般用于dao层)
上面的四个注解功能是一样的,可以混用
步骤:
1.引入依赖
2.开启组件扫描
<?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="com"></context:component-scan>
</beans>
2.属性的注入
1.@AutoWired:根据属性类型进行自动注入
①.把service和对象进行创建,在类中添加创建对象的注解
②.在service类中创建dao对象,在Service中添加dao类型属性,使用注解
2.@Qualifier:根据属性的名称自动注入
要和AutoWirted一起使用
3.@Resource:可以根据类型注入,也可以根据名称注入
4.@Value:注入普通类型属性
@Service
public class service {
@Value(value = "王小鸡")
private String name;
/*@Autowired //根据类型进行注入
@Qualifier(value = "userDaoImpl")
private UserDao userDao;*/
//@Resource//根据类型注入
@Resource(name = "userDaoImpl") //根据名称注入
private UserDao userDao;
public void add() {
System.out.println("add..."+name);
userDao.add();
}
}
3.完全注解开发
1.创建配置类
@Configuration //作为配置类,替代xml配置文件
@ComponentScan(basePackages = {"com.atguigu"})
public class SpringConfig {}
2.编写测试类
@Test
public void test2(){
//加载配置类
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
service service = context.getBean("service", service.class);
System.out.println(service);
service.add();
}