Spring boot 依赖注入
Spring boot 依赖注入
yan5845hao 发表于7个月前
Spring boot 依赖注入
  • 发表于 7个月前
  • 阅读 18
  • 收藏 0
  • 点赞 0
  • 评论 0

腾讯云 技术升级10大核心产品年终让利>>>   

编写普通类

package com.uwo.spring.boot.bean;

/**
 * Created by yanhao on 2017/5/22.
 */
public class Uwo {

    private String username;

    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

第一种使用使用@Configuration与@Bean构建bean

package com.uwo.spring.boot.configuration;
import com.uwo.spring.boot.bean.Uwo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
 * Created by yanhao on 2017/5/22.
 */
@Configuration
public class UwoConfiguration {
    @Bean
    public Uwo getUwo(){
        Uwo uwo = new Uwo();
        uwo.setUsername("uwo-YH");
        uwo.setPassword("uwo123");
        return uwo;
    }
}

第二种使用使用@Configuration与@ImportResource构建bean

// 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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="uwo" class="com.uwo.spring.boot.bean.Uwo">
        <property name="username" value="uwo1"/>
        <property name="password" value="uwo123456"/>
    </bean>
</beans>
// 代码部分
package com.uwo.spring.boot.configuration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
/**
 * Created by yanhao on 2017/5/22.
 */
@Configuration
@ImportResource("classpath:spring.xml")
public class UwoConfiguration {

}

使用代码

package com.uwo.spring.boot.controller;
import com.uwo.spring.boot.bean.Uwo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by yanhao on 2017/5/22.
 */
@Controller
public class AuthController {
    @Autowired
    private Uwo uwo;
    @RequestMapping("/")
    @ResponseBody
    public String auth(){
        return "hello, " + uwo.getUsername();
    }
}
共有 人打赏支持
粉丝 7
博文 102
码字总数 20648
×
yan5845hao
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: