虽然不简单但还是要学的JavaWeb—Spring_IOC

初学,如果有错误,欢迎大家指正。
IOC :控制反转,spring框架的核心之一
即,将对象的创建权交给spring来管理。

1.导入spring的核心包
|___Beans
|___Core
|___Context
|___Expression

2.配置applicationContext.xml
配置好beans标签

<bean id="" class=""></bean>

id属性为bean的名称信息
class属性为实体类的路径。

获取bean:
方法一(手动获取):

ApplicationContext ac = new ClassPathXmlApplicationContext(application.xml);    
Object object = ac.getBean("配置文件中bean的id");
object.function();

方式二(自动扫描+注解)

applicationContext.xml中只需要配置自动扫描
<context:component-scan base-package="要扫描的路径"></context:component-scan>
在bean的类名上方添加注解@Component(value="该bean的id") 此处的value属性代表bean的id。
首先在需要使用该bean的类的类名上方添加注解@ContentConfiguration("applicationContext.xml")
将配置文件引入。然后在类的声明上添加注解@AutoWired(默认按类型装配) 或者@AutoWired @Qualifier(value="")(强制使用名称)与Resource(name="bean的ID")相同。
eg:

bean
@Component(value="Person")
class Person{
    private String name;
    private int age;

    public String getName(){
        return name;
    }
    public void setName(String name){
        this.name = name;   
    }   
}

service 实现类
@Component(value="userServiceImpl")
public void UserServiceImpl implements UserService{

    @AutoWired
    @Qualifier(value="Person")
    private Person person;

    public void showName(){
        person.setName("小王");
        System.out.println(person.getName);
    }
}

test 测试类
@ContentConfiguration("applicationContext.xml")
public class Test{

    @Resource(name="userServiceImpl")
    private UserServiceImpl userImpl;

    public static void main(String args[]){
        userImpl.showName();    
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值