代码及结构jar包
Dao.java
package com.orange.test;
import org.springframework.stereotype.Repository;
/**
* 数据访问层使用的注解
* 默认示例化吃的类是类名并且将首字母改成小写
* 默认实例化出来的类是单例的
*/
@Repository
public class Dao {
public void insert() {
System.out.println("dao insert...");
}
}
Service0.java
package com.orange.test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
/**
* 业务层使用的注解
* 可自定义实例化出的类名
*/
@Service("serviceAAA")
@Scope("prototype") //每次示例都是新的对象
public class Service0 {
@Autowired //注入属性
private Dao dao;
public void setDao(Dao dao) {
this.dao = dao;
}
public void add() {
dao.insert();
}
}
Test.java
package com.orange.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* spring 零配置
*/
public class Test {
public static void main(String[] args) {
ApplicationContext context1 = new ClassPathXmlApplicationContext("beans.xml");
Dao dao1= (Dao)context1.getBean("dao");
Dao dao2= (Dao)context1.getBean("dao");
Service0 serviceAAA1= (Service0)context1.getBean("serviceAAA");
Service0 serviceAAA2= (Service0)context1.getBean("serviceAAA");
//dao1和dao2是同一个对象
System.out.println(dao1);
System.out.println(dao2);
//serviceAAA1和serviceAAA2不是同一个对象,每次返回新的对象
System.out.println(serviceAAA1);
System.out.println(serviceAAA2);
//测试dao类是否被注入
serviceAAA1.add();
}
}
beans.xml
<?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-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<!-- 对 com.orange.test 下的类扫描交给spring管理-->
<context:component-scan base-package="com.orange.test"></context:component-scan>
</beans>
执行结果:
com.orange.test.Dao@596c2a
com.orange.test.Dao@596c2a
com.orange.test.Service0@cc70f8
com.orange.test.Service0@cdc74
dao insert...
打印dao insert...说明dao类已经注入,否则会报java.lang.NullPointerException异常。