Spring基于注解的IoC和DI
配置自动扫描的包
<?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">
<context:component-scan base-package="com.ttpfx"/>
</beans>
Bean注解
- @Component(["beanId"])
- @Controller(["beanId"]) 用于表现层
- @Service(["beanId"]) 用于业务层
- @Repository(["beanId"]) 用于持久层
若不指定,则Bean的id为首字母小写的类名:accountServiceImpl
@Component("accountService")
public class AccountServiceImpl implements AccountService {
// ...
}
等价于:
<bean id="accountService" class="com.ttpfx.service.AccountServiceImpl"/>
Bean的作用域
- @Scope
@Component("accountService")
@Scope("singleton")
public class AccountServiceImpl implements AccountService {
// ...
}
等价于:
<bean id="accountService" class="com.ttpfx.service.AccountServiceImpl" scope="singleton"/>
生命周期
- @PostConstruct 用于注解初始化方法,相当于bean标签的init-method属性
- @PreDestroy 用于注解销毁方法,相当于bean标签的destroy-method属性
@Component("accountService")
public class AccountServiceImpl implements AccountService {
@PostConstruct
private void init() {
System.out.println("AccountServiceImpl.init() 执行");
}
@PreDestroy
private void destroy() {
System.out.println("AccountServiceImpl.destroy() 执行");
}
}
等价于:
<bean id="accountService" class="com.ttpfx.service.AccountServiceImpl" init-method="init" destroy-method="destroy"/>
注入
- @Autowired: 首先根据类型匹配,若该类型的bean不唯一,再根据变量名进行匹配
- @Qualifier("beanId"):注解成员属性时,不能单独使用,需要与@Autowired配合使用;根据beanId匹配
- @Resource(name="beanId"):可单独使用,根据beanId匹配
- @Value("value"):注入基本类型或String
@Component("accountService")
public class AccountServiceImpl implements AccountService {
@Autowired
@Qualifier("accountDao2")
private AccountDao accountDao;
}
@Component("accountService")
public class AccountServiceImpl implements AccountService {
@Resource(name = "accountDao2")
private AccountDao accountDao;
}
@Component("account")
public class Account {
@Value("1")
private Integer id;
@Value("ZhangSan")
private String username;
}
配置类
- @Configuration 注解当前类为配置类
- @ComponentScan("package") 注解自动扫描的包
- @ComponentScans([@ComponentScan])
- @Bean([name = "beanId"]) 注解方法的返回值为Bean类
- @Import(Config.class) 导入配置类
- @PropertySource("classpath:path") 导入properties配置文件,"classpath:"表示从类路径下加载配置文件
@Configuration
@Import({JdbcConfig.class})
@ComponentScans({@ComponentScan("com.ttpfx")})
public class SpringConfig {
}
@Configuration
@PropertySource("classpath:jdbc.properties")
public class JdbcConfig {
@Value("${jdbc.driver}")
private String jdbcDriver;
@Value("${jdbc.url}")
private String jdbcUrl;
@Value("${jdbc.username}")
private String jdbcUsername;
@Value("${jdbc.password}")
private String jdbcPassword;
@Bean(name = "queryRunner")
@Scope("prototype")
public QueryRunner createQueryRunner(DataSource dataSource) {
return new QueryRunner(dataSource);
}
@Bean(name = "dataSource")
public DataSource createDataSource() {
try {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(jdbcDriver);
dataSource.setJdbcUrl(jdbcUrl);
dataSource.setUser(jdbcUsername);
dataSource.setPassword(jdbcPassword);
return dataSource;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
等价于:
<?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">
<context:component-scan base-package="com.ttpfx"/>
<bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner">
<constructor-arg name="ds" ref="dataSource"/>
</bean>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.cj.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/t_mybatis"/>
<property name="user" value="root"/>
<property name="password" value="123456"/>
</bean>
</beans>