Spring注解开发
在Spring4之后,要使用注解开发,必须要保证AOP的包导入了。使用注解开发需要在配置文件里面导入context约束,增加注解支持,并开启注解。
xml比较万能,维护简单方便,使用于很多复杂的场景。
注解(annotation),减少繁琐的xml配置,有一定的局限性,维护相对复杂。
新建一个module
参考之前的博客,Spring06-son-annotation
POJO
package com.pojo;
import lombok.ToString;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
/**
* Component:这个注解等价在bean里面注册了一个bean。
* ToString:lombok的注解,自动生成toString()
* Scope:作用域注解,里面的值可以参考官方文档,常用值为singleton,prototype
*/
@Component
@ToString
@Scope("singleton")
public class User {
@Value("Clay")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Dao
package com.dao;
import org.springframework.stereotype.Repository;
/**
* 这个注解用在Dao层上面。类似与@Component,不过在Dao习惯用这个注解
*/
@Repository
public class UserDao {
}
Service
package com.service;
import org.springframework.stereotype.Service;
/**
* 这个注解用在Service层上面。类似与@Component,不过在Service习惯用这个注解
*/
@Service
public class UserService {
}
Controller
package com.controller;
import org.springframework.stereotype.Controller;
/**
* 这个注解用在Controller层上面。类似与@Component,不过在Controller习惯用这个注解
*/
@Controller
public class UserController {
}
配置文件
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--开启注解-->
<context:annotation-config/>
<!--开启组件扫描。扫描指定包下面的所有类,只要有被@Component以及其衍生注解标注的类,都会被注册到IOC容器里面-->
<context:component-scan base-package="com"/>
</beans>
测试类
package com;
import com.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
@Test
public void test() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = applicationContext.getBean("user", User.class);
System.out.println(user.toString());
}
}
User(name=Clay)
Process finished with exit code 0
@Component
标记该类为一个组件,这个注解一般放在类上,说明这个类被IOC容器管理了,已经成了一个bean。
使用时需要在配置文件里面开启组件扫描
<!--开启组件扫描。扫描指定包下面的所有类,只要有被@Component以及其衍生注解标注的类,都会被注册到IOC容器里面-->
<context:component-scan base-package="com"/>
@Value(“值”)
这个注解用在类的属性或者set方法上,表示该属性被自动注入某个值。类似
<prototype name="属性名" value="值"/>
当然比较复杂的注入还是可以用配置文件
@Component的衍生注解
我们在web开发中会按照mvc三层架构分层,即
- dao 【@Repository】
- service【@Service】
- controller【@Controller】
这四个注解功能都是一样,都是表示将某个类注册在IOC容器里面,都必须开启component的扫描
@Autowired
自动装配注解,详情参考上一节。
@Scope
用在类上面。作用域注解,里面的值可以参考官方文档,常用值为单例singleton,原型prototype