一、前提
注解配置和xml配置要实现的功能都是一样的,都是要降低程序间的耦合,只是配置的形式不一样
实际的开发中到底使用xml还是注解,每家公司有着不同的使用习惯
二、入门
1、环境搭建
1.1 导入jar包
在基于注解的配置中,我们还要多拷贝一个aop的jar包
1.2 添加约束
xmlns:context="http://www.springframework.org/schema/context"
<?xml version="1.0" encoding="UTF-8"?>
<!-- 导入schema 约束的位置在: ..\spring-framework-4.2.4.RELEASE\docs\spring-framework-reference\html\xsd-configuration.html
文件中 -->
<!-- 注意:要导入schema约束 -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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>
1.3 开启spring对注解ioc的支持
开启注解组件扫描
<context:component-scan base-package="com.itheima"/>
<?xml version="1.0" encoding="UTF-8"?>
<!-- 导入schema 约束的位置在: ..\spring-framework-4.2.4.RELEASE\docs\spring-framework-reference\html\xsd-configuration.html
文件中 -->
<!-- 注意:要导入schema约束 -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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 ">
<!-- 告知spring框架在读取配置文件,创建容器时,扫描注解,依据注解创建对象,并存入容器中 -->
<context:component-scan base-package="com.itheima"/>
</beans>
1.4 编写java类
import org.springframework.stereotype.Component;
@Component(value="userService")// 不写的时候,默认的id是:当前类名,且首字母小写
public class UserServiceImpl implements UserService {
@Override
public void saveUser() {
System.out.println("添加用户");
}
}
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.itheima.service.UserService;
public class TestAnnotation {
@Test
public void testName() throws Exception {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService service = (UserService) applicationContext.getBean("userService");
service.saveUser();
}
}
三、常用注解
1、类上的注解
1.1 创建对象的
- @Component
- Spring中提供@Component的三个衍生注解
- @Controller -- 作用在WEB层
- @Service -- 作用在业务层
- @Repository -- 作用在持久层
- Spring中提供@Component的三个衍生注解
1.2 生命周期
- @Scope(value="prototype")
- 指定bean的作用范围
- 取值
- singleton---单例模式,默认,service,dao层
- prototype--多例模式,web层
- reques
- session
- globalsession
- @PostConstruct
- 指定初始化方法
- @PreDestroy
- 指定销毁方法
2、依赖注入
2.1 普通值
- @Value("普通值")
2.2 引用值
- 按照类型注入
- @Autowired
- 按照名称注入
- @Autowired
- @Qualifier("名称")
- 按照名称注入
- @Resource("名称")
3、如何选择
注解的优势
配置简单,维护方便(我们找到类,就相当于找到了对应的配置)
XML的优势
修改时,不用改源码
4、注解和XML混合使用
- 将所有的bean都配置在XML文件中
- 将所有的依赖都使用注解
- 在核心配置文件中,添加<context:annotation-config/>(只能使注入注解生效)
- <context:component-scan base-package="com.itheima"/>可以使@Component生效,注入注解自动生效
spring纯注解配置
类上
- @Configuration
- 用于指定当前类是一个配置类,会从该类上加载注解。读取该类上@ ComponentScan注解初始化spring容器
- PropertySource
- 加载.properties文件中的配置
- value[]:用于指定properties文件位置。如果是在类路径下,需要写上classpath:
- @Import(C3P0Utils.class)
- 导入其他配置类
- @ComponentScan
- 用于指定spring在初始化容器时要扫描的包
- basePackages:用于指定要扫描的包。和该注解中的value属性作用一样
- value:用于指定要扫描的包,是一个数组类型
- 用于指定spring在初始化容器时要扫描的包
方法上
- @Bean
- 使用此方法创建一个对象,并且放入spring容器
- name:给当前@Bean注解方法创建的对象指定一个名称(即bean的id)
案例
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
@Configuration // 当前类是一个配置类
@ComponentScan(basePackages = "com.itheima") // 配置需要扫描注解的包
public class SpringConfiguration {
@Bean// 在spring4.3以前都需要提供一个占位符配置器,开启@PropertySource注解
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/crm
jdbc.username=root
jdbc.password=root
import javax.sql.DataSource;
import org.apache.tomcat.dbcp.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component(value = "c3p0Utils")
@PropertySource("classpath:jdbc.properties")
public class C3P0Utils {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean(name = "datasource")
public DataSource getDataSource() {
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName(driver);
ds.setUrl(url);
ds.setUsername(username);
ds.setPassword(password);
return ds;
}
}
import javax.sql.DataSource;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.itheima.config.SpringConfiguration;
import com.itheima.service.UserService;
public class TestAnnotation {
@Test
public void test() throws Exception {
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
DataSource ds = (DataSource) ac.getBean("datasource");
System.out.println(ds.getConnection());
}
}
spring整合junit测试
导入jar包
spring-test-4.2.4.RELEASE.jar
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.itheima.dao.UserDao;
import com.itheima.domain.User;
@Component(value="userService")
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public void saveUser() {
userDao.saveUser();
}
@Override
public List<User> findAllUser() {
return userDao.findAllUser();
}
}
import java.util.List;
import org.springframework.stereotype.Repository;
import com.itheima.domain.User;
@Repository
public class UserDaoImpl implements UserDao {
@Override
public void saveUser() {
System.out.println("添加用户成功");
}
@Override
public List<User> findAllUser() {
System.out.println("查找所有用户");
return null;
}
}
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.itheima.service.UserService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={UserServiceTest.class})
@Configuration
@ComponentScan("com.itheima")
public class UserServiceTest {
@Autowired
private UserService service;
@Test
public void testSaveUser() throws Exception {
service.saveUser();
}
}