上一篇:Spring框架的IOC学习
1、基于注解的IOC配置
学习基于注解的 IoC 配置,首先得有一个认知,即注解配置和 xml 配置要实现的功能都是一样的,都是要降低程序间的耦合。只是配置的形式不一样。关于实际的开发中到底使用 xml 还是注解,每家公司有着不同的使用习惯。所以这两种配置方式都需要掌握。
需要注意的是:
①使用注解注入时,set 方法不用写。
②基于注解整合时,导入约束时需要多导入一个 context 名称空间下的约束。
<?xml version="1.0" encoding="UTF-8"?>
<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.atlantis"></context:component-scan>
// .....
</beans>
1.1、用于创建对象的注解
相当于:<bean id="" class="">
1.1.1、@Component
把资源交给 Spring 来管理,即相当于在 xml 中配置了一个 bean。
value 属性指定 bean 的 id。如果不指定 value 属性,默认 bean 的 id 是当前类的类名,首字母小写。
@Component("accountDao")
public class AccountDaoImpl implements AccountDao {
public void saveAccount() {
System.out.println("保存了账户");
}
}
1.1.2、@Controller、@Service和@Repository
这三个注解都是针对一个的衍生注解,其作用及属性都是一模一样的。只不过提供了更加明确的语义化。@Controller
一般用于表现层的注解,@Service
一般用于业务层的注解,@Repository
一般用于持久层的注解。
如果注解中有且只有一个属性要赋值时,且名称是 value,则 value 在赋值时可以省略不写。
@Service
public class AccountServiceImpl implements AccountService {
private AccountDao accountDao;
public void saveAccount() {
accountDao.saveAccount();
}
}
1.2、用于注入数据的注解
相当于:<property name="" ref="">
和<property name="" value="">
1.2.1、@Autowired
自动按照类型注入。当使用注解注入属性时,set 方法可以省略。它只能注入其他 bean 类型。当有多个类型匹配时,使用要注入的对象变量名称作为 bean 的 id,在 Spring 容器查找,找到了也可以注入成功。找不到就报错。
1.2.2、@Qualifier
在自动按照类型注入的基础之上,再按照 Bean 的 id 注入。它在给字段注入时不能独立使用,必须和@Autowire
一起使用;但是给方法参数注入时,可以独立使用。
1.2.3、@Resource
直接按照 Bean 的 id 注入。它也只能注入其他 bean 类型。name 属性指定 bean 的 id。
1.2.4、@Value
注入基本数据类型和 String 类型数据。value 用于指定值。
1.3、用于改变作用范围的注解:@Scope
相当于:<bean id="" class="" scope="">
@Scope
指定 bean 的作用范围。value 指定范围的值(singleton、prototype、request、session 或 globalsession)。
1.4、和生命周期相关的注解(了解)
1.4.1、@PostConstruct
用于指定初始化方法。
1.4.2、@PreDestroy
用于指定销毁方法。
2、关于 Spring 注解和 XML 的选择问题
注解的优势:配置简单,维护方便(找到类,就相当于找到了对应的配置)。
xml 的优势:修改时,不用改源码。不涉及重新编译和部署。
Spring 管理 Bean 方式的比较:
xml配置 | 注解配置 | |
---|---|---|
bean定义 | <bean id="" class=""> | @Component,衍生类@Controller @Service @Repository |
bean名称 | 通过 id 或 name 指定 | @Component(“value”) |
bean注入 | <property> 或通过p命名空间 | @Autowired按类型注入,@Qualifier按名称注入 |
生命过程、bean作用范围 | init-method,destroy-method,范围 scope 属性 | @PostConstruct初始化,@PreDestroy销毁,@Scope设置作用范围 |
适合场景 | bean 来自第三方 | bean的实现类由用户自己开发 |
3、新注解说明
3.1、@Configuration
用于指定当前类是一个 Spring 配置类,当创建容器时会从该类上加载注解。获取容器时需要使用AnnotationApplicationContext(有@Configuration 注解的类.class)。
@Configuration
public class SpringConfiguration {
// ...
}
要注意的是,此时我们已经把配置文件用类来代替了,但是如何配置创建容器时要扫描额包呢?需要用到下面的注解@ComponentScan
。
3.2、@ComponentScan
用于指定 Spring 在初始化容器时要扫描的包。作用和在 spring 的 xml 配置文件中的:
<context:component-scan base-package="com.atlantis"/>
是一样的。
@Configuration
@ComponentScan("com.atlantis")
public class SpringConfiguration {
}
我们已经配置好了要扫描的包,但是数据源和 JdbcTemplate 对象如何从配置文件中移除呢?需要用到下面的注解@Bean
。
3.3、@Bean
该注解只能写在方法上,表明使用此方法创建一个对象,并且放入 Spring 容器。
public class JdbcConfig {
/**
* 创建一个数据源,并存入 spring 容器中
*/
@Bean(name="dataSource")
public DataSource createDataSource() {
try {
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setUser("root");
ds.setPassword("root");
ds.setDriverClass("com.mysql.jdbc.Driver");
ds.setJdbcUrl("jdbc:mysql:///spring");
return ds;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 创建一个 DBAssit,并且也存入 spring 容器中
*/
@Bean(name="dbAssit")
public DBAssit createDBAssit(DataSource dataSource) {
return new DBAssit(dataSource);
}
}
我们已经把数据源和 DBAssit 从配置文件中移除了,此时可以删除 bean.xml 了。但是由于没有了配置文件,创建数据源的配置又都写死在类中了。如何把它们配置出来呢?需要用到下面的注解@PropertySource
。
3.4、@PropertySource
用于加载.properties 文件中的配置。例如我们配置数据源时,可以把连接数据库的信息写到 properties 配置文件中,就可以使用此注解指定 properties 配置文件的位置。
value[]
用于指定 properties 文件位置。如果是在类路径下,需要写上classpath:
。
public class JdbcConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
/**
* 创建一个数据源,并存入 spring 容器中
*/
@Bean(name="dataSource")
public DataSource createDataSource() {
try {
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setDriverClass(driver);
ds.setJdbcUrl(url);
ds.setUser(username);
ds.setPassword(password);
return ds;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
jdbc.properties 文件:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring
jdbc.username=root
jdbc.password=root
此时我们已经有了两个配置类,但是他们还没有关系。如何建立他们的关系呢?
请看下一个注解@Import
。
3.5、@Import
用于导入其他配置类,在引入其他配置类时,可以不用再写@Configuration 注解。当然,写上也没问题。value[]
用于指定其他配置类的字节码。
@Configuration
@ComponentScan(basePackages = "com.atlantis.spring")
@Import({ JdbcConfig.class})
public class SpringConfiguration {
}
@Configuration
@PropertySource("classpath:jdbc.properties")
public class JdbcConfig{
}
通过注解获取容器
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);