1.什么是注解
①:注解是代码特殊标记,格式:@注解名称(属性名称=属性值,属性名称=属性值...)
②:使用注解,注解作用在类上面,方法上面,属性上边
③:使用注解的目的:简化XML配置
2.Spring针对Bean管理中创建对象提供的注解
@Component 普通的类
@Controller 表现层
@Service 业务层
@Repository 持久层
*上边四个功能一样,都可以用来创建bean实例
3.用注解的方式创建对象
①:编写接口和实现类
package com.qcby.testanno;
public interface UserService {
public void hello();
}
②:在需要管理的类上添加@Component注解
package com.qcby.testanno;
import org.springframework.stereotype.Component;
/* <bean id="us" class="UserServiceImpl"/> */
/**
* 组件,作用:把当前类使用IOC容器进行管理,如果没有指定名称,默认使用类名,首字母是小写。
* userServiceImpl。或者自己指定名称
**/
@Controller(value="us")
public class UserServiceImpl implements UserService {
public void hello() {
System.out.println("使用注解,方便吧!");
}
}
③:编写配置文件,重点是开启注解扫描。
<?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">
<!--开启注解扫描 com.qcby所有的包中的所有的类-->
<context:component-scan base-package="com.qcby"/>
</beans>
编写测试方法
package com.qcby.test;
import com.qcby.testanno.UserService;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Demo2 {
@Test
public void run1(){
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("ApplicationContextanno.xml");
UserService us = (UserService) ac.getBean("us");
us.hello();
}
}