Spring框架的两大核心:反转控制IOC和依赖注入DI
IOC: 打个比方,本来创建对象需要由程序员自己去new一个新的构造方法,现在由第三方Spring来创建
DI: 简而言之,对象的属性已经注入到了XML中,直接拿来用就可以了
这里来个例子:
public class spring1//这里只是创建一个spring1类
{
private string str;
public void getstr{return str;}
public void setstr(string str){this.str = str ;}
}
//这里注入str的值
<?
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:aop
=
"http://www.springframework.org/schema/aop"
xmlns:tx
=
"http://www.springframework.org/schema/tx"
xmlns:context
=
"http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<
bean
name
=
"s"
class
=
"spring1"
>
<
property
name
=
"str"
value
=
"I'm okay !"
/>
</
bean
>
</
beans
>
public class test
{
public static void main(string[] args)
{
ApplicationContext context =
new
ClassPathXmlApplicationContext(
new
String[] {
"applicationContext.xml"
});
spring1
s = (spring1) context.getBean(
"s"
);//此处体现了IOC
System.out.println(s.getstr());
}
}
.使用Spring的IOC,将对象之间的依赖关系交给Spring,降低组件之间的耦合性,让我们更专注于应用逻辑,具体的好处我还没体会到。
Spring的注解非常重要,可以减少对XML文件的工作,比如上述中xml文件的
<
bean
name
=
"s"
class
=
"spring1"
>
<
property
name
=
"str"
value
=
"I'm okay !"
/>
</
bean
>
可以直接采用注解的方式省略,这里直接是对bean的注解
1spring1中必须有
@Component来注解,表明此类为bean
具体如下@Component public class spring1
2 上述xml中改为
<context:component-scan base-
package
=
"spring1"
/>
<context:component-scan base-
package
=
"com.how2java.pojo"
/>
3 private string str 需要改为 private string str=“I'm okay@!”
<context:component-scan base-
package
=
"com.how2java.pojo"
/>