入门案例
try {
//读取配置文件
InputStream in = TestSpring.class.getClassLoader().
getResourceAsStream("application.properties");
Properties properties = new Properties();
properties.load(in);
//将properties中所有的键值对存入到map
map = new HashMap<>();
Set<Object> set = properties.keySet();
for(Object key : set) {
//根据键获取对应的值
String property = properties.getProperty(key.toString());
//将值反映成对象
Class aClass = Class.forName(property);
Object o = aClass.newInstance();
//将对象存放到map集合中
map.put(key, o);
}
} catch(Exception e) {
e.printStackTrace();
}
}
public static Object getObj(String key) {
return map.get(key);
}
使用Bean标签生成对象
方式1:
<!--
id 为唯一标识
class 指定全限定名称
scope 用于设置单例和多列 默认为singleton(单例)
lazy-init 指定加载方式 默认为立即加载
-->
<bean id="demo" class="cn.itcast.demo.Demo"></bean>
方式2:通过方法的调用来生成对象
public class Demo2 {
public Demo get() {
Demo demo = new Demo();
return demo;
}
}
<!—- 相当于 Demo2 demo2 = new Demo2() -->
<bean id="demo2" class="cn.itcast.demo.Demo2"></bean>
<!-- 相当于 demo2.get() -->
<bean id="demo" factory-bean="demo2" factory-method="get"></bean>
方式3:通过静态方法的调用来生成对象
public class Demo2 {
public static Demo get() {
Demo demo = new Demo();
return demo;
}
}
<!-- 相当于Demo2.get() -->
<bean id="demo2" class="cn.itcast.demo.Demo2" factory-method="get"></bean>
依赖注入
- 构造方法注入
<bean id="demo" class="cn.itcast.demo.Demo">
<!--
<constructor-arg> 用于为构造方法进行参数注入
name 指参数名
value 为注入基本类型设置值
ref 为引用(对象)类型设置值
-->
<constructor-arg name="name" value="tom"></constructor-arg>
<constructor-arg name="age" value="18"></constructor-arg>
<constructor-arg name="birthday" ref="now"></constructor-arg>
</bean>
<bean id="now" class="java.util.Date"></bean>
- Set方法进行注入
public class Demo {
private String name;
private int age;
private Date birthday;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
<bean id="demo" class="cn.itcast.demo.Demo">
<!--
通过property标签对 set方法进行参数的注入
name 指定set方法
value 为注入基本类型设置值
ref 为引用(对象)类型设置值
-->
<property name="name" value="tom"></property>
<property name="age" value="18"></property>
<property name="birthday" ref="now"></property>
</bean>
<bean id="now" class="java.util.Date"></bean>
对象生成型注解
@Repository
@Component
@Service
@Controller
@Configuration
//注类型的注解用于将修辞的类放入bean容器之中
//相当于生成代码 <bean id="类名(首字母小写)" class="所修辞类的全限定名">
@Bean
//将方法的返回类型载入到bean容器之中
//相当于生成代码 <bean id="方法名" class="方法返回类型的全限定名">
注入数据类型注解(用于自动匹配装载bean容器中对应的类型)
第1种 对象类型注入
@Autowired
如果有容器中有多个类型与之对应可通过加入@Qualifier(“”)注解进行选择匹配装载
@Resource
如果有容器中有多个类型与之对应可通过@Resource(name=””) name属性进行选择匹配装载
第2种 基本数据类型与字符串类型注入
@Value(“数据”)
通过@Value直接注入即可