一. ioc的注解配置:
1. 注解分类:
(1):用于创建对象的注解:
①:Component:
——作用:用于把当前类对象存入spring容器中;
——属性value:用于指定bean的id。当我们不写时,它的默认值是当前类名,且首字母改小写。
②:Controller:一般用在表现层
③:Service:一般用在业务层
④:Repository:一般用在持久层
⑤:说明:Controller、Service、Repository这三个注解的作用和Component完全相同。
(2):用于依赖注入的注解:
①:Autowired:
——作用:自动按照类型注入。只要容器中有唯一的一个bean对象类型和要注入的变量类型匹配,就可以注入成功;如果ioc容器
中没有任何bean的类型和要注入的变量类型匹配,则报错;如果Ioc容器中有多个类型匹配时遵循类中的变量名(多态);
——出现位置:可以是变量上,也可以是方法上;
——细节:在使用注解注入时,set方法就不是必须的了;
——使用:
@Autowired
private IAccountDao accountDao;
②:Qualifier:
——作用:在按照类中注入的基础之上再按照名称注入,好处是不用修改变量名;
——细节:必须和@Autowired一起使用;
——使用:
@Autowired
@Qualifier("accountDao")
private IAccountDao accountDao;
③:Resource(name = "accountDao")
——作用:按照bean的id名注入数据;
——细节:可以单独使用;
——使用:
@Resource(name = "accountDao")
private IAccountDao accountDao;
④:Value("要注入的值")
——作用:注入基本数据和String类型;
——细节:可用SpEL表达式(${});
——使用:
@Value("value注入")
private String name;
(3):用于改变作用范围的注解:
Scope("prototype"或"singleton")
——作用:指定bean的作用范围;
——使用:
@Scope("prototype")
public class AccountService
(4):和生命周期有关的:
①:PreDestroy
——作用:用于指定销毁的方法;
——使用:
@PreDestroy
public void destroy(){
System.out.println("对象销毁了");
}
②:PostConstruct
——作用:用于指定初始化方法;
——使用:
@PostConstruct
public void init(){
System.out.println("对象初始化了");
}
2. Spring新注解:
(1):Configuration
——作用:指定配置类;
——细节:当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可以不写;
——使用:直接在类上面加
(2):ComponentScan
——作用:指定创建容器时要扫描的包
——使用:
@ComponentScan(basePackages = {"cn.xupt"})
(3):Bean
——作用:用于把当前方法的返回值作为bean对象存入spring的ioc容器中;
——属性:name:用于指定bean的id。当不写时,默认值是当前方法的名称;
——细节:当我们使用注解配置方法时,如果方法有参数,spring框架会去容器中查找有没有可用的bean对象,查找的方式和Autowired注解的作用是一样的;
——使用:
@Bean(name = "accountService")
public AccountService createAccountService(){
return new AccountService();
}
(4):Import
——作用:用于导入其他的配置类;
——细节:当我们使用Import的注解之后,有Import注解的类就父配置类,而导入的都是子配置类;
——使用:
@Import(JDBCconfig.class)
(5):PropertySuorce
——作用:用于指定properties文件的位置;
——使用:
@PropertySource("classpath:jdbc.properties")
3. Spring整合junit的配置
1、导入spring整合junit的jar(坐标)
2、使用Junit提供的一个注解把原有的main方法替换了,替换成spring提供的@Runwith:
@RunWith(SpringJUnit4ClassRunner.class)
3、告知spring的运行器,spring和ioc创建是基于xml还是注解的,并且说明位置:使用@ContextConfiguration:
locations:指定xml文件的位置,加上classpath关键字,表示在类路径下;
@ContextConfiguration(locations = "classpath:bean.xml")
classes:指定注解类所在地位置。
@ContextConfiguration(classes = SpringConfiguration.class)