Spring——个人理解1
Spring是一个存储Bean的容器。但不像AndroidStudio那样自动化,需要编写applicationContext.xml
// 标签配置方式
对于bean标签需要找到和标记。--- class,id
对于property标签需要找到和赋值 -- name,value(ref)
--------------------------------------------------------------------------------------
// 注解配置方式
我们知道,spring容器配置标签:需找到和标记
spring因此提供注解配置:在配置的类上加入注解解决找到问题。注解中输入id解决标志问题
@Component("") ----通用解决bean标记问题
@Repository()语义化userDao对象
@Service()语义化UserService对象
@Controller()语义化servlet对象
@AutoWired()解决属性找到问题
@Qualifier(String ref)解决属性赋值问题
@Value(String value)解决属性赋值问题
那么bean标签的找到和标记问题解决了。需要application吗?
需要:application需要知道在哪寻找这些被注解标记的类
applicationContext.xml内首先加入域,
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"
通过
让Spring知道到那找被标记的类
--------------------------------------------------------------------------------------------------
#标签注解方式,applicationContext.xml使用新标签代替
@Configuration :用于标记被代替的ApplicationContext.xml
@ComponentScan(String packPath):用于标识要搜索的包范围
bean对象的操作同注解配置方式
----------------------------------------------------------------------------------------------------
Junit测试Spring
每次都调用Application application在Spring里很麻烦。
Spring结合Junit,让测试类不需要new ApplicationContext(),并且Bean可以通过注解直接变成成员变量
1. @RunWith(SpringJUnit4ClassRunner.class)
测试类上的固定写法
2. @ContextConfiguration("classpath:applicationContext.xml")
通过注解找到Context
@ContextConfiguration(class={SpringConfiguration.class})
通过注解找到Context.class
3. @AutuWirted
注入对象
使用
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class SpringJunitTest { //要测谁,就注入谁 @Autowired private UserService userService; @Test public void test1(){ userService.save(); } }