Spring使用注解开发
1、@Component注解
@Component是用来创建对象的注解
(1)spring文件设置约束
<?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">
</beans>
(2)扫描包
<!--指定注解扫描包-->
<context:component-scan base-package="com.workhah.pojo"/>
扩展
<!--开启组件扫描-->
<context:component-scan base-package="com.workhah">
<!-- 设置扫描的注解 -->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<!-- 设置不扫描的注解 -->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
</context:component-scan>
(3)编写实体类并添加注解
- @Component 直接使用创建的对象的 id 为当前类名且首字母小写
- @Component(“user”) 设置参数创建的对象的 id 为该参数名
// 相当于配置文件中 <bean id="user" class="com.workhah.pojo.User"/>
@Component("user")
public class User {
// 相当于配置文件中 <property name="name" value="workhah"/>
@Value("workhah")
public String name;
}
2、@Component衍生注解
这三个注解跟@Component功能相同。
- @Controller:web层
- @Service:service层
- @Repository:dao层
3、@Scope
bean的作用域
- singleton:(默认)每一个Spring IoC容器都拥有唯一的一个实例对象
- prototype: 一个Bean定义,任意多个对象
- request:一个HTTP请求会产生一个Bean对象,也就是说,每一个HTTP 请求都有自己的Bean实例。只在基于web的Spring ApplicationContext中可用
- session:限定一个Bean的作用域为HTTPsession的生命周期。同样,只有基于web的Spring ApplicationContext才能使用
@Controller("user")
@Scope("prototype")
public class User {
@Value("workhah")
public String name;
}
不用注解
<bean id="user" class="com.workhah.pojo.User" scope="prototype">
<property name="name" value="workhah"/>
</bean>
4、配置类
(1)创建配置类,替代 xml 配置文件
@Configuration //作为配置类,替代 xml 配置文件
@ComponentScan(basePackages = {"com.workhah"})
public class SpringConfig {
}
(2)测试类
@Test
public void testService2() {
//加载配置类
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
UserService userService = context.getBean("userService", UserService.class);
System.out.println(userService);
userService.add();
}
5、JavaConfig
JavaConfig 原来是 Spring 的一个子项目,它通过 Java 类的方式提供 Bean 的定义信息。
(1)编写实体类
@Component
public class Dog {
@Value("dog")
private String name;
public String getName() {
return this.name;
}
}
(2)编写MyConfig配置类
@Configuration //代表这是一个配置类
public class MyConfig {
//通过方法注册一个bean,这里的返回值就Bean的类型,方法名就是bean的id!
@Bean
public Dog dog(){
return new Dog();
}
}
(3)测试
@Test
public void test(){
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MyConfig.class);
Dog dog = applicationContext.getBean("dog",Dog.class);
System.out.println(dog.getName());
}