注解开发
整合第三方技术(重点)
注解整合MyBatis分析
- 业务类使用注解形式声明bean,属性采用注解注入
- 建立独立的配置管理类,分类管理外部资源,根据功能进行分类,并提供对应的方法获取bean
- 使用注解形式启动bean扫描,加载所有注解配置的资源(bean)
- 使用AnnotationConfigApplicationContext对象加载所有的启动配置类,内部使用导入方式进行关联
注解整合MyBatis步骤
1.修改mybatis外部配置文件格式为注解格式
public interface AccountDao {
@Insert("insert into account(name,money)values(#{name},#{money})")
void save(Account account);
@Delete("delete from account where id = #{id} ")
void delete(Integer id);
@Update("update account set name = #{name} , money = #{money} where id = #{id} ")
void update(Account account);
@Select("select * from account")
List<Account> findAll();
@Select("select * from account where id = #{id} ")
Account findById(Integer id);
}
2.业务类使用@Service声明bean,使用@Autowired注入对象
@Service("accountService")
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
}
3.编写Spring配置类:SpringConfig,并加载properties文件
@Configuration
@PropertySource("classpath:jdbc.properties")
public class SpringConfig {
}
4.建立配置文件JDBCConfig与MyBatisConfig类,并将其导入到核心配置类SpringConfig
数据源配置类:JDBCConfig
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;
@Bean(value = "dataSource")
public DataSource getDataSource(){
DruidDataSource ds = new DruidDataSource();
ds.setDriverClassName(driver);
ds.setUrl(url);
ds.setUsername(userName);
ds.setPassword(password);
return ds;
}
}
MyBatis配置类:MyBatisConfig
public class MyBatisConfig {
@Bean
public SqlSessionFactoryBean getSqlSessionFactoryBean(@Autowired DataSource dataSource){
SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
ssfb.setTypeAliasesPackage("com.ithe.domain");
ssfb.setDataSource(dataSource);
return ssfb;
}
@Bean
public MapperScannerConfigurer getMapperScannerConfigurer(){
MapperScannerConfigurer msc = new MapperScannerConfigurer();
msc.setBasePackage("com.ithe.dao");
return msc;
}
}
5.开启注解扫描,将JDBCConfig与MyBatisConfig类导入到核心配置类SpringConfig中
@Configuration
@ComponentScan("com.ithe")
@PropertySource("classpath:jdbc.properties")
@Import({JDBCConfig.class,MyBatisConfig.class})
public class SpringConfig {
}
6.使用AnnotationConfigApplicationContext对象加载配置项
public class App {
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
AccountService accountService = (AccountService) ctx.getBean("accountService");
Account ac = accountService.findById(3);
System.out.println(ac);
}
}
注解整合Junit
1.导入Spring整合Junit坐标,从Spring5.0以后,要求Junit的版本必须是4.12及以上
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
2.Spring接管Junit的运行权,使用Spring专用的Junit类加载器
@RunWith(SpringJUnit4ClassRunner.class)
3.加载Spring配置类
@ContextConfiguration(classes = SpringConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class UserServiceTest {
@Test
public void testSave() {}
}
IoC底层核心原理
5.1)IoC核心接口
查看类文件:Ctrl+n
查看类结构:Ctrl+h
查看内部结构:Alt+7
-
BeanFactory接口
-
HierarchicalBeanFactory接口
-
AutowireCapableBeanFactory接口
-
ListableBeanFactory
组件扫描器
- 开发过程中,需要根据需求加载必要的bean,排除指定bean
设定组件扫描加载过滤器
-
名称:@ComponentScan
-
类型:类注解
-
位置:类定义上方
-
作用:设置spring配置加载类扫描规则
-
范例:
@ComponentScan( value="com.ithe", //设置基础扫描路径 excludeFilters = //设置过滤规则,当前为排除过滤 @ComponentScan.Filter( //设置过滤器 type= FilterType.ANNOTATION, //设置过滤方式为按照注解进行过滤 classes=Service.class) //设置具体的过滤项,过滤所有@Service修饰的bean )
excludeFilters:设置排除性过滤器
includeFilters:设置包含性过滤器
type:设置过滤器类型:ANNOTATION, CUSTOM
bean初始化过程解析(理解)
-
BeanFactoryPostProcessor
-
作用:定义了在bean工厂对象创建后,bean对象创建前执行的动作,用于对工厂进行创建后业务处理
-
运行时机:当前操作用于对工厂进行处理,仅运行一次
public class MyBeanFactory implements BeanFactoryPostProcessor { @Override //工厂后处理bean接口核心操作 public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { //第1阶段 System.out.println("第1阶段:采购手机屏幕和电池..."); } }
-
注意:导入自定义的MyBeanFactory
@Configuration @ComponentScan("com.ithe") @Import(MyBeanFactory.class) public class SpringConfig {...}
-
-
BeanPostProcessor
-
作用:定义了所有bean初始化前后进行的统一动作,用于对bean进行创建前业务处理与创建后业务处理
-
运行时机:当前操作伴随着每个bean的创建过程,每次创建bean均运行该操作
public class MyBean implements BeanPostProcessor { //所有bean初始化前置操作 public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { //第2阶段 System.out.println(beanName); System.out.println("第2阶段:检查手机屏幕和电池是否正常"); return bean; } //所有bean初始化后置操作 public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { //第4阶段 System.out.println("第4阶段:检查手机功能是否正常"); return bean; } }
@Configuration @ComponentScan("com.ithe") @Import({MyBeanFactory.class, MyBean.class}) public class SpringConfig { }
-
-
InitializingBean
-
作用:定义了每个bean的初始化前进行的动作,属于非统一性动作,用于对bean进行创建前业务处理
-
运行时机:当前操作伴随着任意一个bean的创建过程,保障其个性化业务处理
@Service("mobileService") public class MobileServiceImpl implements MobileService, InitializingBean { @Override public void create() { System.out.println("手机要出厂啦..."); } @Override //定义当前bean初始化操作,功效等同于init-method属性配置 public void afterPropertiesSet() { //第3阶段 System.out.println("第3阶段:购买红外设备"); } }
-