Spring到底是什么东西呢?Java中常说的Spring能干些啥?

什么是spring?

1、spring在百度百科是这样介绍的:Spring是一个开源框架,它由Rod Johnson创建。它是为了解决企业应用开发的复杂性而创建的。
工作需要,需要用到Java语言,自学没多久,看到Spring框架的时候,就觉得挺模糊的,什么是框架,能干什么,为什么要用框架而不直接用包和类实现各个模块呢?
在了解spring之前,先了解一下JAVABEAN。JavaBean是用java语言写的一种组件,我们可以使用JavaBean中的属性、方法和事件。换一种说法就是JavaBean就是你知道他的功能是什么,用就好了,而不必管它的实现。
然后Spring呢,就是用来装JavaBean的一种容器。说白了就是用来管理JavaBean实例化对象的一种容器。

spring中使用JavaBean

1、首先需要添加springIDE插件,配置相关依赖,具体教程网上遍地是,这里附上一个(spring-IDE插件配置)。

pom.xml  (1.spring-context   2.spring-orm  3.spring-web  4.spring-aspects)

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>zking</groupId>
<artifactId>s1</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>s1 Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.1.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.0.1.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.0.1.RELEASE</version>
</dependency>
</dependencies>
<build>
<finalName>s1</finalName>
</build>
</project>

2、 插件Spring的xml文件(右键–>new–>other–>spring–>Spring Bean Configuration File)
注:创建spring的XML文件时,需要添加beans/aop/tx/context标签支持(勾上即可)

ApplicationContext.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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

</beans>

3、随便创建一个类

package test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class HelloWorld {
private String name;

public HelloWorld() {
super();
System.out.println("new HelloWorld()");
}

public HelloWorld(String name) {
super();
this.name = name;
}

public void init() {
System.out.println("init.......");
}
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}
如何在spring当中配置定义一个JavaBean

使用无参构造方法+set方法创建一个JavaBean
1 id:在容器中查找Bean(对象)的id(唯一、且不能以/开头)
2 class:bean(对象)的完整类名
3 name:在容器中查找Bean(对象)的名字(唯一、允许以/开头、允许多个值,多个值之间用逗号或空格隔开)
4 scope:(singleton|prototype)默认是singleton
4.1 singleton(单例模式):在每个Spring IoC容器中一个bean定义对应一个对象实例
4.2 prototype(原型模式/多例模式):一个bean(对象)定义对应多个对象实例
4 abstract:将一个bean定义成抽象bean(抽象bean是不能实例化的),抽象类一定要定义成抽象bean,非抽象类也可以定义成抽象bean
5 parent:指定一个父bean(必须要有继承关系才行)
6 init-method:指定bean对象()的初始化方法
7 使用有参数构造方法创建javaBean(java对象):constructor-arg

然后再xml创造bean

<bean id="helloworld" class="p1.HelloWorld" scope="prototype" name="a b c" init-method="init">
<property name="name">
<value>zs</value>
</property>

</bean>

之后写一个main测试一下即可。

public static void main(String[] args) {
	ApplicationContext applicationContext=new ClassPathXmlApplicationContext("ApplicationContext.xml");
	HelloWorld a = (HelloWorld)applicationContext.getBean("a");
	System.out.println("你好: "+a.getName());

	HelloWorld b = (HelloWorld)applicationContext.getBean("b");
	System.out.println("你好: "+b.getName());

	HelloWorld c = (HelloWorld)applicationContext.getBean("c");
	System.out.println("你好: "+c.getName());

	HelloWorld d = (HelloWorld)applicationContext.getBean("helloworld2");
	System.out.println("你好: "+d.getName());
}

Spring 容器会自动完成@bean对象的实例化。

创建应用对象之间的协作关系的行为称为:装配(wiring),这就是依赖注入的本质。

Spring 三种配置方案

1.在XML中进行显示配置
2.使用Java代码进行显示配置
3.隐式的bean发现机制和自动装配

鉴于第三种方法比较常用,这里实现一下第三种方法:
1.组件扫描(component scanning):Spring 会自动发现应用上下文中所创建的bean。
2.自动装配(autowiring):Spring自动满足bean之间的依赖。

package com.stalkers;

/**
 * CD唱片接口
 * Created by stalkers on 2016/11/17.
 */
public interface ICompactDisc {
    void play();
}
package com.stalkers.impl;

import com.stalkers.ICompactDisc;
import org.springframework.stereotype.Component;

/**
 * Jay同名专辑
 * Created by stalkers on 2016/11/17.
 */
@Component
public class JayDisc implements ICompactDisc {

    private String title = "星晴";

    public void play() {
        System.out.println(title + ":一步两步三步四步,望着天上星星...");
    }
}

Component注解作用:
表明该类会作为组件类。

不过,组件扫描默认是不开启用的,我们还需要显示配置下Spring,从而命令它去寻找带有@Component注解的类,并为其创建bean。

1.java code开启组件扫描:
其中,如果CompoentScan后面没有参数的话,默认会扫描与配置类相同的包

@Configuration
@ComponentScan
public class CDPlayerConfig {
    @Bean
    public ICompactDisc disc() {
        return new JayDisc();
    }
}

2.xml启动组件扫描

<?xml version="1.0" encoding="utf-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context.xsd">
    <context:component-scan base-package="com.stalkers.impl"/>
</beans>

测试代码

package com.stalkers;

import com.stalkers.config.CDPlayerConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * Created by stalkers on 2016/11/18.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = CDPlayerConfig.class)
public class TestPlay {
    @Autowired
    private ICompactDisc jayDisc;

    @Test
    public void play() {
        jayDisc.play();
    }
}

在ComponentScan扫描的包中,所有带有@Component注解的类都会创建为bean

为组件扫描的bean命名
Spring应用上下文种所有的bean都会给定一个ID。在前面的例子中,尽管我们没有明确地为JayDisc bean设置ID,但是Spring会默认为JayDisc设置ID为jayDisc,也就是将类名的第一个字母变成小写。

如果想为这个bean设置不同的ID,那就将期望的值传递给@Component注解

@Component("zhoujielun")
public class JayDisc implements ICompactDisc {
  ...
}

如果不使用@Component注解的话,则使用Java依赖注入规范(Java Dependency Injection)中所提供的@Named注解bean的ID。

需要引入:

<dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
        </dependency>
@Named("zhoujielun")
public class JayDisc implements ICompactDisc {
  ....
}

设置组件扫描的基础包
前面再给CDPlayerConfig类设置@ComponentScan,我们并没有设置任何属性,这个时候默认扫描默认包是:CDPlayerConfig类所在包及其包的子包。

如果是下图这种情况,DisConfig与其这时候就需要设置@ComponentScan的扫描的包。
在这里插入图片描述

@Configuration
@ComponentScan(basePackages = {"com.stalkers.soundsystem"})
public class DiscConfig {
}

basePackages使用的是复数,则意味着可以设置多个基础包。

但是basePackages后面跟的是String类型,这种类型并不安全。可以使用basePackageClasses有下面这种写法:

@Configuration
@ComponentScan(basePackageClasses = {com.stalkers.soundsystem.JayCompactDisc.class})
public class DiscConfig {
}

通过为bean添加注解实现自动装配
如果所有的对象都是独立的,彼此之间没有任何依赖,那么使用组件扫描就能自动化装配bean。

但是实际工作中,很多对象会依赖其他对象完成任务。这时候就需要能够将组件扫描得到的bean和他们依赖装配在一起。这就是自动装配(autowiring)

使用Spring的Autowired

public interface IMediaPlayer {
    void play();
}
@Component
public class CDPlayer implements IMediaPlayer {

    private ICompactDisc cd;
    
    @Autowired
    public CDPlayer(ICompactDisc cd) {
        this.cd = cd;
    }

    public void play() {
        System.out.println("cd Play:");
        cd.play();
  }

CDPlayer类的构造器上添加了@Autowired注解,表明当Spring创建CDPlayerbean的时候,会通过这个构造器来进行实例化

Autowired的多种方式
1.构造器注解(constructor)

2.属性setter注解

3.field注解

不管使用上面3中的哪个方法,Spring都会满足声明的依赖。假如有且只有一个bean匹配依赖的话,那么这个bean将会被装配进来。

如果使用2,3方式注解,有多个bean的话,则用Qualifier指定。

如果没有匹配的bean,那么在应用上下文创建的时候,Spring会抛出一个异常。为了避免异常的出现,可以使用

@Autowired(required = false)
private IMediaPlayer CDPlayer;

required=false表示如果没有匹配的话,Spring会让bean处于未装配的样子。使用未装配的属性,会出现NullPointerException

总结:
所以在使用开发的时候一般建议使用Resource(package javax.annotation)进行注解。但是Resource不支持构造器注解

Spring Security 是一个基于 Spring 框架的安全框架,它提供了一系列的安全服务,例如认证(Authentication)、授权(Authorization)、攻击防护等。通过 Spring Security,我们可以轻松地实现对应用程序的身份验证和授权管理。 在 Java 项目中使用 Spring Security,需要在 pom.xml 文件中添加相应依赖,例如: ```xml <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>5.4.2</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>5.4.2</version> </dependency> ``` 配置 Spring Security 的方式有多种,其中最常用的是 Java 配置方式。我们可以创建一个继承自 WebSecurityConfigurerAdapter 的配置类,并重写其中的一些方法来配置 Spring Security。 例如,以下代码展示了如何通过 Java 配置方式启用 HTTP Basic 认证: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .anyRequest().authenticated() .and() .httpBasic(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("user").password("{noop}password").roles("USER"); } } ``` 上述代码中,configure 方法用于配置 HTTP 安全策略,这里的策略是要求所有请求都需要认证;configureGlobal 方法用于配置认证管理器,这里使用了一个基于内存的认证管理器,并添加了一个用户名为 user,密码为 password 的用户。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值