欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring思路梳理2--基于黑马程序员--Spring中的bean

程序员文章站 2022-03-30 13:17:49
...

1.Bean的实例化:以构造器方式为例

通过默认的无参构造方法

package com.itheima.instance.constructor
public class Bean1{
}

注:xml文件的引用的约束均省略

<beans>
<bean id="bean1" class="con,itheima.instance,contructor.Bean1"/>
</beans>

测试类InstanceTest1

package com.itheima.instance.contructor
import org,springframe.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class InstanceTset1(String[] args){
	//定义配置文件路径
	String xmlPath = "com/itheima/instance/ClassPathXmlApplicationCOntext";
	//ApplicationContext在加载配置文件时,对Bean进行初始化
	ApplicationContext applicationContext =
	    new ClassPathXmlApplicationContext(xmlPath);
	Bean1 bean = (Bean1) applicationContext.getBean("bean1");
	System.out.println("bean");
}

对其中几个名字的解释:Bean1为类名,bean1为spring容器中对应的bean的名字,可用getBean()引用,bean则为实例化的对象

2.Bean的作用域

主要介绍,singleton(单例,默认)和prototype(原型)

通过<Bean>元素的scope属性指定

<bean id="scope" class="com.itheima.scope.Scope" scope="singleton"/>

3.Bean的装配:以基于注解为例

package com.itheima.annotation;
public interface UserDao{
	public void save();
}

package com.itheima.annotation;
package com.itheima.annotation;
import org.springframework.sterotype.Repository;
@Repository("userDao")
public class UserDaoImpl implements UserDao{
	public void save(){
		System.out.println("userdao...save");
	}
}
package com.itheima.annotation;
import javax.annotation.Resource;
import org.springframework.sterotype.Controller;
@Repository("userDao")
public class UserController{
	@Resource(name="userService")
	private UserService userService;
	public void save(){
		this.userService.save();
		System.out.println("userController....save....");
	}
	
}
<beans>
<!-- 使用Context命名空间,通知Spring扫描指定包下所有Bean类,进行注解解析 -->
<context:component-scan base-package="com.itheima.annotation"/>
</Beans>
package com.itheima.annotation;
import org.springframework.context.ApplicationContext;
import 
    org.springframework.context.support.ClassPathXmlApplicationContext;
public classs AnnotationAssembleTest{
	public void main(String[] args){
		String xmlPath = "com/itheima/annotation/bean6.xml";
		ApplicationContext applicationContext =
		     new ClassPathXmlApplicationContext(xmlPath);
	    //获取UserController实例
		UserController userController =
		(UserController) applicationContext.getBean("userController");
		//调用userController的save()方法
		userController.save();
	}
} 

输出结果

userDao...save

userService...save..

userController...save..

程序注释:@Repository,@Service,@Controller分别在数据访问层(DAO层),业务层(Service层),控制层(Controller)标识了Spring中的Bean,@Resource则是对Bean进行装配